|
| 1 | +import math |
| 2 | +from sympy import * |
| 3 | + |
| 4 | +x = symbols('x') |
| 5 | +y = symbols('y') |
| 6 | + |
| 7 | +def taylorexpansion(func,a,n,var): |
| 8 | + t_y = symbols('t_y') |
| 9 | + expansion = func.subs(var,a) |
| 10 | + d = func |
| 11 | + if(expansion==0): |
| 12 | + n+=1 |
| 13 | + try: |
| 14 | + k=1 |
| 15 | + while (k<n): |
| 16 | + d = diff(d,var) |
| 17 | + term = (d*((t_y-a)**k))/factorial(k) |
| 18 | + term = term.subs(var,a) |
| 19 | + if(term==0): |
| 20 | + continue |
| 21 | + term = term.subs(t_y,var) |
| 22 | + expansion=term+expansion |
| 23 | + k+=1 |
| 24 | + if(d==0 and k<n): |
| 25 | + print("only ",k-1," terms present") |
| 26 | + if n<1: |
| 27 | + print("3rd argument denotes number of terms and should be a natural number") |
| 28 | + return '' |
| 29 | + expansion = expansion.subs(t_y,var) |
| 30 | + return expansion |
| 31 | + except TypeError: |
| 32 | + print("3rd argument denotes number of terms and should be a natural number") |
| 33 | + return '' |
| 34 | + |
| 35 | +def taylorvalue(func,a,n,x): |
| 36 | + f=taylorexpansion(func,a,n,x) |
| 37 | + return f.evalf(subs={x:a}) |
| 38 | + |
| 39 | +def mclaurianexpansion(func,steps,variable): |
| 40 | + taylorexpansion(func,0,steps,variable) |
| 41 | + |
| 42 | +def mclaurianvalue(func,steps,variable): |
| 43 | + taylorvalue(func,0,steps,variable) |
| 44 | + |
| 45 | +def examples(): |
| 46 | + # e^x expansion at point x=0 with 5 terms differentiating with respect to x |
| 47 | + pprint(taylorexpansion(exp(x),0,5,x)) |
| 48 | + |
| 49 | + # e^x approximation at point x=1 with 10 terms differentiating with respect to x |
| 50 | + print(taylorvalue(exp(x),1,10,x)) |
| 51 | + |
| 52 | + # log(1+x) expansion at point x=0 with 5 terms differentiating with respect to x |
| 53 | + pprint(taylorexpansion(log(x+1),0,5,x)) |
| 54 | + |
| 55 | + # sin(x) expansion at point x=0 with 5 terms differentiating with respect to x |
| 56 | + pprint(taylorexpansion(sin(x),0,5,x)) |
| 57 | + |
| 58 | + # expansion for expression at point x=0 with 3 terms differentiating with respect to x |
| 59 | + pprint(taylorexpansion((5*x**2)+(3*x)+(7),0,3,x)) |
| 60 | + |
| 61 | + # e^(xy) expansion at point x=1 with 5 terms differentiating with respect to x |
| 62 | + pprint(taylorexpansion(exp(x*y),1,5,x)) |
| 63 | + |
| 64 | +examples() |
0 commit comments