def tim_nghiem(f, x, a, b, eps=1e-8, N=1000):
    iter = 1
    deriv = Derivative(f, x).doit()
    deriv_a = deriv.subs({x:a})
    deriv_b = deriv.subs({x:b})
    m = min([deriv_a, deriv_b])
    M= max([deriv_a, deriv_b])
    nd_deriv = Derivative(deriv, x).doit()
    nd_deriv_a = nd_deriv.subs({x:a})
    nd_deriv_b = nd_deriv.subs({x:b})
    
    #kiem tra dieu kien
    if deriv_a*deriv_b < 0 or nd_deriv_a*nd_deriv_b< 0:
        return float('NaN'), 0
    
    #tim xap xi ban dau x0 va d
    if f.subs({x:a}) * nd_deriv.subs({x:a}) < 0:
        x0 = a
        d = b
    else:
        x0 = b
        d = a
    x_n_1 = x0
    x_n = x_n_1 - (d-x_n_1) / (f.subs({x:d}) - f.subs({x:x_n_1})) * f.subs({x:x_n_1})
    print('iter = {}: x_n = {}'.format(iter, x_n))
    while math.fabs(x_n - x_n_1) > m*eps/(M - m):
        x_n_1 = x_n
        x_n = x_n - (d-x_n) / (f.subs({x:d}) - f.subs({x:x_n})) * f.subs({x:x_n})
        iter += 1
        print('iter = {}: x_n = {}'.format(iter, x_n))
    return x_n, iter
Example #2
0
def tim_nghiem(f, x, a, b, eps=1e-8, N=1000): #gia su ham f tren (a,b) la loi hoac lom
    iter = 1
    deriv = Derivative(f, x).doit()
    deriv_a = deriv.subs({x:a})
    deriv_b = deriv.subs({x:b})
    nd_deriv = Derivative(deriv, x).doit()
    nd_deriv_a = nd_deriv.subs({x:a})
    nd_deriv_b = nd_deriv.subs({x:b})
    m = min([deriv_a, deriv_b])
    M = max([deriv_a, deriv_b])
    
    #kiem tra dieu kien
    if deriv_a*deriv_b < 0 or nd_deriv_a*nd_deriv_b< 0:
        return float('NaN'), 0
    
    #tim xap xi ban dau x0
    if f.subs({x:a})*nd_deriv_a > 0:
        x0 = a
    else:
        x0 = b
    x_n_1 = x0
    x_n = x_n_1 - f.subs({x:x_n_1}) / deriv.subs({x:x_n_1})
    print('iter = {}: x_n = {}'.format(iter, x_n))
    while math.fabs(x_n - x_n_1) > math.sqrt(2*m*eps/M):
        x_n_1 = x_n
        x_n = x_n_1 - f.subs({x:x_n_1}) / deriv.subs({x:x_n_1})
        iter += 1
        print('iter = {}: x_n = {}'.format(iter, x_n))
    return x_n, iter
Example #3
0
def test_ODE_1():
    l = Function('l')
    r = Symbol('r')

    e = Derivative(l(r),r)/r+Derivative(l(r),r,r)/2- \
        Derivative(l(r),r)**2/2
    sol = dsolve(e, [l(r)])
    assert (e.subs(l(r), sol)).expand() == 0

    e = e * exp(-l(r)) / exp(l(r))
    sol = dsolve(e, [l(r)])
    assert (e.subs(l(r), sol)).expand() == 0
Example #4
0
def test_ODE_1():
    l = Function('l')
    r = Symbol('r')

    e = Derivative(l(r),r)/r+Derivative(l(r),r,r)/2- \
        Derivative(l(r),r)**2/2
    sol = dsolve(e, [l(r)])
    assert (e.subs(l(r), sol)).expand() == 0

    e = e*exp(-l(r))/exp(l(r))
    sol = dsolve(e, [l(r)])
    assert (e.subs(l(r), sol)).expand() == 0
Example #5
0
def test_derivative_subs():
    f = Function('f')
    g = Function('g')
    assert Derivative(f(x), x).subs(f(x), y) != 0
    # need xreplace to put the function back, see #13803
    assert Derivative(f(x), x).subs(f(x), y).xreplace({y: f(x)}) == \
        Derivative(f(x), x)
    # issues 5085, 5037
    assert cse(Derivative(f(x), x) + f(x))[1][0].has(Derivative)
    assert cse(Derivative(f(x, y), x) +
               Derivative(f(x, y), y))[1][0].has(Derivative)
    eq = Derivative(g(x), g(x))
    assert eq.subs(g, f) == Derivative(f(x), f(x))
    assert eq.subs(g(x), f(x)) == Derivative(f(x), f(x))
    assert eq.subs(g, cos) == Subs(Derivative(y, y), y, cos(x))
Example #6
0
def test_derivative_subs():
    f = Function('f')
    g = Function('g')
    assert Derivative(f(x), x).subs(f(x), y) != 0
    # need xreplace to put the function back, see #13803
    assert Derivative(f(x), x).subs(f(x), y).xreplace({y: f(x)}) == \
        Derivative(f(x), x)
    # issues 5085, 5037
    assert cse(Derivative(f(x), x) + f(x))[1][0].has(Derivative)
    assert cse(Derivative(f(x, y), x) +
               Derivative(f(x, y), y))[1][0].has(Derivative)
    eq = Derivative(g(x), g(x))
    assert eq.subs(g, f) == Derivative(f(x), f(x))
    assert eq.subs(g(x), f(x)) == Derivative(f(x), f(x))
    assert eq.subs(g, cos) == Subs(Derivative(y, y), y, cos(x))
Example #7
0
def test_deriv_sub_bug3():
    x = Symbol('x')
    y = Symbol('y')
    f = Function('f')
    pat = Derivative(f(x), x, x)
    assert pat.subs(y, y**2) == Derivative(f(x), x, x)
    assert pat.subs(y, y**2) != Derivative(f(x), x)
Example #8
0
def test_deriv_sub_bug3():
    x = Symbol('x')
    y = Symbol('y')
    f = Function('f')
    pat = Derivative(f(x), x, x)
    assert pat.subs(y, y**2) == Derivative(f(x), x, x)
    assert pat.subs(y, y**2) != Derivative(f(x), x)
Example #9
0
def test_deriv_sub_bug3():
    x = Symbol("x")
    y = Symbol("y")
    f = Function("f")
    pat = Derivative(f(x), x, x)
    assert pat.subs(y, y**2) == Derivative(f(x), x, x)
    assert pat.subs(y, y**2) != Derivative(f(x), x)
Example #10
0
def test_deriv_sub_bug3():
    x = Symbol("x")
    y = Symbol("y")
    f = Function("f")
    pat = Derivative(f(x), x, x)
    assert pat.subs(y, y**2) == Derivative(f(x), x, x)
    assert pat.subs(y, y**2) != Derivative(f(x), x)
Example #11
0
def get_foc():
    jData = request.get_json()
    retData = {}
    c_points = []
    x = Symbol('x')
    Xt = jData['init_func']
    retData['init_func'] = Xt
    derivative_data = []
    try:
        d1 = Derivative(Xt, x).doit()
        retData['d1'] = printing.latex(d1)
        d2 = Derivative(Xt, x, 2).doit()
        retData['d2'] = printing.latex(d2)
        # critical_points = solve(d1)
        # print(critical_points)
        # for idx,c in enumerate(critical_points):
        # 	retData['critical_points_'+str(idx)] = str(round(d2.subs({x:c}).evalf(),3))
        # print('found max mins')
        for c in range(-100, 100, 1):
            new_row = []
            new_row.append((c / 20))
            new_row.append((round((sympify(Xt)).subs({x: c / 20}).evalf(), 4)))
            new_row.append((round(d1.subs({x: c / 20}).evalf(), 4)))
            new_row.append((round(d2.subs({x: c / 20}).evalf(), 4)))
            if c / 20 == 3 or c / 20 == -3:
                new_row.append((round((sympify(Xt)).subs({
                    x: c / 20
                }).evalf(), 4)))

            else:
                new_row.append(None)
            derivative_data.append(new_row)
        print('created data')
        retData['forViz'] = str(derivative_data)
    except SympifyError:
        print('Parsing error')
        error_msg = {'error': "Incorrect function. Please rectify."}
        return jsonify(success=False, data=error_msg)
    except:
        print('Doesn\' t exist')
        error_msg = {'error': 'Doesn\' t exist'}
        return jsonify(success=False, data=error_msg)

    return jsonify(success=True, data=retData)
Example #12
0
def test_subs_in_derivative():
    expr = sin(x*exp(y))
    u = Function('u')
    v = Function('v')
    assert Derivative(expr, y).subs(expr, y) == Derivative(y, y)
    assert Derivative(expr, y).subs(y, x).doit() == \
        Derivative(expr, y).doit().subs(y, x)
    assert Derivative(f(x, y), y).subs(y, x) == Subs(Derivative(f(x, y), y), y, x)
    assert Derivative(f(x, y), y).subs(x, y) == Subs(Derivative(f(x, y), y), x, y)
    assert Derivative(f(x, y), y).subs(y, g(x, y)) == Subs(Derivative(f(x, y), y), y, g(x, y)).doit()
    assert Derivative(f(x, y), y).subs(x, g(x, y)) == Subs(Derivative(f(x, y), y), x, g(x, y))
    assert Derivative(f(x, y), g(y)).subs(x, g(x, y)) == Derivative(f(g(x, y), y), g(y))
    assert Derivative(f(u(x), h(y)), h(y)).subs(h(y), g(x, y)) == \
        Subs(Derivative(f(u(x), h(y)), h(y)), h(y), g(x, y)).doit()
    assert Derivative(f(x, y), y).subs(y, z) == Derivative(f(x, z), z)
    assert Derivative(f(x, y), y).subs(y, g(y)) == Derivative(f(x, g(y)), g(y))
    assert Derivative(f(g(x), h(y)), h(y)).subs(h(y), u(y)) == \
        Derivative(f(g(x), u(y)), u(y))
    assert Derivative(f(x, f(x, x)), f(x, x)).subs(
        f, Lambda((x, y), x + y)) == Subs(
        Derivative(z + x, z), z, 2*x)
    assert Subs(Derivative(f(f(x)), x), f, cos).doit() == sin(x)*sin(cos(x))
    assert Subs(Derivative(f(f(x)), f(x)), f, cos).doit() == -sin(cos(x))
    # Issue 13791. No comparison (it's a long formula) but this used to raise an exception.
    assert isinstance(v(x, y, u(x, y)).diff(y).diff(x).diff(y), Expr)
    # This is also related to issues 13791 and 13795; issue 15190
    F = Lambda((x, y), exp(2*x + 3*y))
    abstract = f(x, f(x, x)).diff(x, 2)
    concrete = F(x, F(x, x)).diff(x, 2)
    assert (abstract.subs(f, F).doit() - concrete).simplify() == 0
    # don't introduce a new symbol if not necessary
    assert x in f(x).diff(x).subs(x, 0).atoms()
    # case (4)
    assert Derivative(f(x,f(x,y)), x, y).subs(x, g(y)
        ) == Subs(Derivative(f(x, f(x, y)), x, y), x, g(y))

    assert Derivative(f(x, x), x).subs(x, 0
        ) == Subs(Derivative(f(x, x), x), x, 0)
    # issue 15194
    assert Derivative(f(y, g(x)), (x, z)).subs(z, x
        ) == Derivative(f(y, g(x)), (x, x))

    df = f(x).diff(x)
    assert df.subs(df, 1) is S.One
    assert df.diff(df) is S.One
    dxy = Derivative(f(x, y), x, y)
    dyx = Derivative(f(x, y), y, x)
    assert dxy.subs(Derivative(f(x, y), y, x), 1) is S.One
    assert dxy.diff(dyx) is S.One
    assert Derivative(f(x, y), x, 2, y, 3).subs(
        dyx, g(x, y)) == Derivative(g(x, y), x, 1, y, 2)
    assert Derivative(f(x, x - y), y).subs(x, x + y) == Subs(
        Derivative(f(x, x - y), y), x, x + y)
Example #13
0
def test_subs_in_derivative():
    expr = sin(x*exp(y))
    u = Function('u')
    v = Function('v')
    assert Derivative(expr, y).subs(expr, y) == Derivative(y, y)
    assert Derivative(expr, y).subs(y, x).doit() == \
        Derivative(expr, y).doit().subs(y, x)
    assert Derivative(f(x, y), y).subs(y, x) == Subs(Derivative(f(x, y), y), y, x)
    assert Derivative(f(x, y), y).subs(x, y) == Subs(Derivative(f(x, y), y), x, y)
    assert Derivative(f(x, y), y).subs(y, g(x, y)) == Subs(Derivative(f(x, y), y), y, g(x, y)).doit()
    assert Derivative(f(x, y), y).subs(x, g(x, y)) == Subs(Derivative(f(x, y), y), x, g(x, y))
    assert Derivative(f(x, y), g(y)).subs(x, g(x, y)) == Derivative(f(g(x, y), y), g(y))
    assert Derivative(f(u(x), h(y)), h(y)).subs(h(y), g(x, y)) == \
        Subs(Derivative(f(u(x), h(y)), h(y)), h(y), g(x, y)).doit()
    assert Derivative(f(x, y), y).subs(y, z) == Derivative(f(x, z), z)
    assert Derivative(f(x, y), y).subs(y, g(y)) == Derivative(f(x, g(y)), g(y))
    assert Derivative(f(g(x), h(y)), h(y)).subs(h(y), u(y)) == \
        Derivative(f(g(x), u(y)), u(y))
    assert Derivative(f(x, f(x, x)), f(x, x)).subs(
        f, Lambda((x, y), x + y)) == Subs(
        Derivative(z + x, z), z, 2*x)
    assert Subs(Derivative(f(f(x)), x), f, cos).doit() == sin(x)*sin(cos(x))
    assert Subs(Derivative(f(f(x)), f(x)), f, cos).doit() == -sin(cos(x))
    # Issue 13791. No comparison (it's a long formula) but this used to raise an exception.
    assert isinstance(v(x, y, u(x, y)).diff(y).diff(x).diff(y), Expr)
    # This is also related to issues 13791 and 13795; issue 15190
    F = Lambda((x, y), exp(2*x + 3*y))
    abstract = f(x, f(x, x)).diff(x, 2)
    concrete = F(x, F(x, x)).diff(x, 2)
    assert (abstract.subs(f, F).doit() - concrete).simplify() == 0
    # don't introduce a new symbol if not necessary
    assert x in f(x).diff(x).subs(x, 0).atoms()
    # case (4)
    assert Derivative(f(x,f(x,y)), x, y).subs(x, g(y)
        ) == Subs(Derivative(f(x, f(x, y)), x, y), x, g(y))

    assert Derivative(f(x, x), x).subs(x, 0
        ) == Subs(Derivative(f(x, x), x), x, 0)
    # issue 15194
    assert Derivative(f(y, g(x)), (x, z)).subs(z, x
        ) == Derivative(f(y, g(x)), (x, x))

    df = f(x).diff(x)
    assert df.subs(df, 1) is S.One
    assert df.diff(df) is S.One
    dxy = Derivative(f(x, y), x, y)
    dyx = Derivative(f(x, y), y, x)
    assert dxy.subs(Derivative(f(x, y), y, x), 1) is S.One
    assert dxy.diff(dyx) is S.One
    assert Derivative(f(x, y), x, 2, y, 3).subs(
        dyx, g(x, y)) == Derivative(g(x, y), x, 1, y, 2)
    assert Derivative(f(x, x - y), y).subs(x, x + y) == Subs(
        Derivative(f(x, x - y), y), x, x + y)
Example #14
0
def GradientDescent(features, targets, loss, bias, weight):
    loss_c_list = []
    loss_m_list = []
    for i in range(25):
        # plt.scatter(features, targets)
        for feature, target in zip(features, targets):
            # plt.scatter(features, targets)

            deriv_c = Derivative(loss, c).doit()
            deriv_m = Derivative(loss, m).doit()

            loss_c = deriv_c.subs([(c, bias), (m, weight), (x, feature),
                                   (y, target)])
            loss_m = deriv_m.subs([(c, bias), (m, weight), (x, feature),
                                   (y, target)]) * feature
            loss_c_list.append(loss_c)
            loss_m_list.append(loss_m)

            summation_loss_c = sum(loss_c_list) / (2 * n)
            summation_loss_m = sum(loss_m_list) / (2 * n)

        updated_c = bias - LR * summation_loss_c
        updated_m = weight - LR * summation_loss_m

        bias = updated_c
        weight = updated_m

        # yy = float(bias + weight*features[sample])
        # print("summation_loss_c", summation_loss_c)
        # print("summation_loss_m", summation_loss_m)
    print("new bias:", bias)
    print("new weight:", weight, '\n')
    print("-------------------------")
    # plt.scatter(features, targets)
    plt.plot(features,
             weight * features + bias,
             label='Gradient Descent',
             color='red')
    plt.legend()
Example #15
0
def test_derivative_subs3():
    x = Symbol('x')
    dex = Derivative(exp(x), x)
    assert Derivative(dex, x).subs(dex, exp(x)) == dex
    assert dex.subs(exp(x), dex) == Derivative(exp(x), x, x)
Example #16
0
px = solve(Ds, x)[0]
py = Fx.subs({x: px})

pprint('( {0}, {1} )'.format(px, py))

# 3.2.6

# A child kicks a soccer ball across a field. The distance between the soccer ball and
# the child in feet is given by the formula:
# p(t) = 25t - t^2, 0 <= t < 25, where t is measured in seconds.
# How fast is the soccer ball moving when t = 5 seconds?

Pt = 25 * t - t**2
t = Symbol('t', positive=True)
d = Derivative(Pt, t).doit()
d.subs({t: 5})

# 3.2.7

# The rate of production at ACME toys can be determined from the production formula P(t) = 1600t - 100t^2,
# where P(t) is the number of units produced in a given time and t is the time in hours since the factory shift
# began. At what time does the rate of toy production stop?

Pt = 1600 * t - 100 * t**2
t = Symbol('t')
d = Derivative(Pt, t).doit()
solve(d, t)[0]

# 3.2.8

# A student goes crabbing after math class. He drops the crab cage, and waits. Let f(t) denote the distance
Example #17
0
from fractions import Fraction

init_printing(order='rev-lex', use_unicode=True)

# 4.3.2

# Find the derivitave: f(x) =(2x)^3 * (3x)^2

Fx = (2 * x)**3 * (3 * x)**2
x = Symbol('x')
Derivative(Fx, x).doit()

# 4.3.3

# Find the derivitave: f(x) = 7 * [ x ^ 7/3 + 11/7*x^7/5 + 13x^7/7 ] ^ 4/3

Fx = 7 * (x**7 / 3 + 11 / 7 * x**7 / 5 + 13 * x**7 / 7)**4 / 3
x = Symbol('x')
Derivative(Fx, x).doit()

# 4.3.9

# A particle's position is given by the function: x(t) = ( 4 - t ) ^ 3.
# What is the value of dx/dt when t = 3 ?

Ft = (4 - t)**3
t = Symbol('t')
Dt = Derivative(Ft, t).doit()
pprint(Dt)
Dt.subs({t: 3})
Example #18
0
f = (Ht1_delta - Ht1) / delta_t

simplify(f)

Limit(f, delta_t, 0).doit()

# 3.1.2

# Suppose f(x) = -2x^2.
# What is the instantaneous rate of change of f(x) when x = 4?

Fx = -2 * x**2
x = Symbol('x')
d = Derivative(Fx, x).doit()
d.subs({x: 4})

# 3.1.3

# A particular bird's flight position in feet is given by the equation P(t) = 12t^2/7 +t, where
# t is the number of seconds that elapse.
# What is the bird's instantaneous velocity when t = a?
Pt = 12 * t**2 / 7 + t
t = Symbol('t')
a = Symbol('a ')
d = Derivative(Pt, t).doit()
d.subs({t: a})

# 3.1.5

# A biker rides along a horizontal straight line with its location given by the fraction,
Example #19
0
 def findTangent(function, value):
     c = Symbol('c')
     deriv = Derivative(function, c).doit()
     derivative_value = deriv.subs({c: value})
     return derivative_value
Example #20
0
def test_deriv_sub_bug3():
    f = Function('f')
    pat = Derivative(f(x), x, x)
    assert pat.subs(y, y**2) == Derivative(f(x), x, x)
    assert pat.subs(y, y**2) != Derivative(f(x), x)
Example #21
0
fBMI = 703 * w / h**2

w_bmi = fBMI.subs({h: height})
bmi = w_bmi.subs({w: weight})

print('raw bmi: {0}'.format(bmi))

target_weight = solve(w_bmi - target_bmi, w)[0]

# a
# Calculate the BMI for a person who weighs 219 pounds and is 6 prime 2 double prime tall.
print('A person that weighs {0}lbs and is {1}in tall has a BMI of {2}'.format(
    weight, height, round(bmi, dec_places)))
# b
# How much weight would the person in part a have to lose to reach a BMI of 24.9​?
print('They would need to loose {0}lbs to reach a BMI of {1}'.format(
    round(weight - target_weight, dec_places), target_bmi))

# c
# For a 126​-lb. ​female, what is the rate of change of BMI with respect to​ height?

weight = 126
dH = Derivative(fBMI.subs({w: weight})).doit()
pprint(dH)

# d
# Calculate f'( 66 ).
height = 66
rate_of_change = float(dH.subs({h: height}))

print('rate of change for female {0}'.format(round(rate_of_change, 2)))
Example #22
0
#To test an​ individual's use of a certain​ mineral, a researcher injects small amount of a radioactive form of that mineral into the​ person's bloodstream.  
#The mineral remaining in the bloodstream is measured each day for several days.  
#Suppose the amount of the mineral remaining in the bloodstream​ (in milligrams per cubic​ centimeter) t days after the initial injection is approximated by 

# C(t) = 1/2 ( 4t + 4) ^ -1/2

# Find the rate of change of the mineral level with respect to time for 7.5 days.

from sympy import symbols, solve, pprint, Derivative, init_printing, pretty
import math

init_printing()

def disp_fun( f ):
	pprint( '\n{0}\n\n'.format( pretty( f ) ) )

t = symbols( 't' )
C = .5*( 4*t + 4 ) ** -(.5)

disp_fun( C )

dC = Derivative( C, t ).doit()

# The rate of change of the mineral level with respect to time for 7.5 days is approximately 
# nothing milligrams per cubic centimeter per day.
​# (Round to two decimal places as​ needed.)

round( dC.subs( { t: 7.5 } ), 2 )
Example #23
0
x = Symbol('x')
f = x**5 - 30 * x**3 + 50 * x

d1 = Derivative(f, x).doit()

critical_points = solve(d1)

critical_points

A = critical_points[2]
B = critical_points[0]
C = critical_points[1]
D = critical_points[3]

d2 = Derivative(f, x, 2).doit()

d2.subs({x: B}).evalf()
d2.subs({x: C}).evalf()
d2.subs({x: A}).evalf()
d2.subs({x: D}).evalf()

x_min = -5
x_max = 5

f.subs({x: C}).evalf()
f.subs({x: A}).evalf()

f.subs({x: x_min}).evalf()
f.subs({x: x_max}).evalf()
# Suppose the demand for a certain item is given by ​D(p) -5p^2 7p +600​, where p represents the price of the item in dollars.

# a. Find the rate of change of demand with respect to price.
# b. Find and interpret the rate of change of demand when the price is ​$10.

from sympy import symbols, Limit, Derivative, Integral

p = symbols('p')
fP = -5 * p**2 - 7 * p + 600

dP = Derivative(fP, p).doit()

# The rate of change of demand with respect to price is
dP

# When the price is ​$10​, demand is:
dP.subs({p: 10})
# decreasing at a rate of about  107 items for each increase in price of​ $1.
Example #25
0
def test_derivative_subs3():
    dex = Derivative(exp(x), x)
    assert Derivative(dex, x).subs(dex, exp(x)) == dex
    assert dex.subs(exp(x), dex) == Derivative(exp(x), x, x)
Example #26
0
init_printing(order='rev-lex', use_unicode=True)

# 4.2.1

# Suppose f (x) = (4x 3 + 3) (1 − x 2 ).
# What is the equation of the line tangent to f at the point (1, 0)?

x0 = 1
y0 = 0

Fx = (4 * x**3 + 3) * (1 - x**2)
x = Symbol('x')
Dx = Derivative(Fx, x).doit()

m = Dx.subs({x: x0})
x1 = Fx.subs({x: x0})

# 4.2.2

# Suppose f (x) = (x 2 − 2x) (3x + 2).
# What is the equation of the line normal to f
# (i.e., the line perpendicular to the tangent line)
# at the point (1, −5)?

x0 = 1
y0 = -5

Fx = (x**2 - 2 * x) * (3 * x + 2)
x = Symbol('x')
Dx = Derivative(Fx, x).doit()
Example #27
0
from sympy import symbols, solve, pprint, Derivative
import math

dec_places = 4
value = .6

x = symbols('x')

fX = (x**2) / (2 * (1 - x))
pprint(fX)

dX = Derivative(fX, x).doit()
pprint(dX)

res = dX.subs({x: value})

# ​(Simplify your answer. Type an integer or decimal rounded to four decimal places as​ needed.)
print('The rate of change for {0} at {1} is {2}'.format(
    fX, value, round(res, dec_places)))
Example #28
0
# 1st Derivative
d1 = Derivative(f, x).doit()
critical_points = solve(d1)
print(critical_points)

A = critical_points[2]
B = critical_points[0]
C = critical_points[1]
D = critical_points[3]

# 2nd Derivative
d2 = Derivative(f, x, 2).doit()

# Substitute values
print(d2.subs({x: B}).evalf())
print(d2.subs({x: C}).evalf())
print(d2.subs({x: A}).evalf())
print(d2.subs({x: D}).evalf())

# Create two labels x_min, and x_max to refer to the domain boundaries and
# evaluate the function at the points A, C, xmin and x_max.
x_min = -5
x_max = 5

print(f.subs({x: A}.evalf()))  # Global Maximum
print(f.subs({x: C}.evalf()))
print(f.subs({x: x_min}.evalf()))
print(f.subs({x: x_max}.evalf()))

print(f.subs({x: B}.evalf()))
Example #29
0
# The distance of a particle from some fixed point is given by the following function.

from sympy import symbols, Limit, Derivative, Integral

def rate_of_change( f, a, b ):
	return ( f.subs( { t: b } ) - f.subs( { t: a } ) ) \
	/ ( b - a )

t,h = symbols( 't,h' )
sT = t**2 + 3*t - 2

a = 5
b = 5

if a == b:
	l = Limit( sT, t, ( a + h ) ).doit()
	d = Derivative( l, h ).doit()
	d.subs( { h: 0 } )
else:
	rate_of_change( sT, a, b )
Example #30
0
def calc_dq(t_i):
    dq = Derivative(q, t)
    dq_t = dq.subs({q: theta, t: t_i, length: 1}).evalf()
    return dq_t
>>> critical_points=solve(d1)
>>> critical_points
[-sqrt(9 - sqrt(71)), sqrt(9 - sqrt(71)), -sqrt(sqrt(71) + 9), sqrt(sqrt(71) + 9)]

          #They correspond to the points B,C,A,D

>>> A=critical_points[2]
>>> B=critical_points[0]
>>> C=critical_points[1]
>>> D=critical_points[3]

          #Now we find the value of f''(x) by substituting the value of each critical point.
          #If  f''(x) is less than 0 we have a maximum, if it's greated than 0 we have a minimum

>>> d2=Derivative(f,x,2).doit()
>>> d2.subs({x:B}).evalf()
127.661060789073
>>> d2.subs({x:C}).evalf()
-127.661060789073
>>> d2.subs({x:A}).evalf()
-703.493179468151
>>> d2.subs({x:D}).evalf()
703.493179468151

          #Points A and C are maxima and B and D are minima

>>> x_min=-5
>>> x_max=5
>>> f.subs({x:A}).evalf()
705.959460380365
>>> f.subs({x:C}).evalf()
Example #32
0
from math import sqrt, exp, log, sin, pi
from sympy import Symbol, Limit, Derivative, solve, sympify, S, simplify, lambdify, pprint, init_printing, symbols
from fractions import Fraction

init_printing(order='rev-lex', use_unicode=True)

# 4.1.1

# Suppose a particle’s position is given by f (t) = t 4,
# where t is measured in seconds and f (t) is given in centimeters. What is the velocity of the particle when t = 3?

Ft = t**4
t = Symbol('t')
Dt = Derivative(Ft, t).doit()
Dt.subs({t: 3})

# 4.1.2

# Suppose f(x) = x^-3. What is f'(x) ?

Fx = x**-3
x = Symbol('x')
Derivative(Fx, x).doit()

# 4.1.3

# Suppose f(x) = x^0. What is f'(x) ?

Fx = x**0.1
x = Symbol('x')
Derivative(Fx, x).doit()
Example #33
0
def test_deriv_sub_bug3():
    f = Function('f')
    pat = Derivative(f(x), x, x)
    assert pat.subs(y, y**2) == Derivative(f(x), x, x)
    assert pat.subs(y, y**2) != Derivative(f(x), x)
Example #34
0
# Assume that a factory smokestack begins emitting a pollutant at 8 a.m. 
# 
# Assume that the pollutant disperses​ horizontally, forming a circle. 
# 
# If t represents the time​ (in hours) since the factory began emitting pollutants​ (t = 0 represents 8​ a.m.), assume that the radius of the circle of pollution is r(t) = 4t miles. 
# 
# Let Upper A( r ) = pi r^2, the area of a circle of radius r. Complete parts​ (a) and​ (b).

from sympy import symbols, solve, pprint, Derivative, init_printing, pretty
import math

init_printing()

def disp_fun( f ):
	pprint( '\n{0}\n\n'.format( pretty( f ) ) )

t, pi = symbols( 't, pi' )

r = 4*t
A = ( r ** 2 ) * pi

disp_fun( A )

dA = Derivative( A, t ).doit()

# dA/dT
disp_fun( dA )

# dA/dT @ t = 6
disp_fun( dA.subs( { t: 6 } ) )