## Taylor Series[HELP]

A forum for general discussion of the Python programming language.

### Taylor Series[HELP]

blablablablablabla... (So... you know cos(x) = 1 - x^2/2! + x^4/4! - x^6/6!....; with this I'm trying to write a code to do this for me with a good nivel of precision...)

Here is my code!
Code: Select all
`def juice(x):    d=2.0    y=1.0    x = float(x)    k = (-1.0)*x**2/d    np = input("Nivel of precision: ")    np = float(np)    while d < (np):        if d % 2 == 0:            d = d*(d-1)            y = k*y + y            # I'm just feeling that my error is here!; I want to take the last sum to multiply it by the constant k...        d = d + 1    return y                `

Could you give me some advice about this code? Please, don't post your code here, if you do this the fun is over..., I'm just seaching the way of think to solve this code.
GabrielSilva

Posts: 8
Joined: Mon May 20, 2013 12:20 am

### Re: Taylor Series[HELP]

I'll offer a couple of suggestions.

I assume that "nivel" means the number of terms that you want to evaluate. I would prompt for "Nivel of precision" outside the function call and pass it as an argument.

Let's assume you are calculating the first four terms and that we are using ^ to mean exponentiation. Other than just using brute-force evaluation, you can re-write the polynomial as:

Code: Select all
`Let k = -(x^2), thencos(x) = 1 + k/2! + k^2/4! + k^3/6!       = 1 + k/(2*1) + k^2/((4*3)*(2*1)) + k^3/((6*5)*(4*3)*(2*1))       = 1 + k/(2*1) + k/(2*1) * k/(4*3) + k/(2*1) * k/(4*3) * k/(6*5)`

It looks like you are using this approach. I think you'll need to remember the current approximation ( y ), the last term ( ?? ), and the value -(x^2). Each time through the loop, you need to update the last term using k and d.

Is this the level of suggestions you wanted?

casevh
casevh

Posts: 114
Joined: Sat Feb 09, 2013 7:35 am

### Re: Taylor Series[HELP]

My first recommendation would be to use a for loop instead of a while loop. Something like:
Code: Select all
`for i in xrange(2,prec*2+1,2):`
Also if all you care about is the expansion then use the math module for the factorials. If you want to manually calculate your factorials then that should be written in a separate function.

Basically this can be one lined if you are stubborn enough (gets a bit ugly though).

-Mek
• Use code tags when posting code.
• Include any errors with your post (in code tags).
• Make examples the minimum length to demonstrate your issue.

Mekire

Posts: 1711
Joined: Thu Feb 07, 2013 11:33 pm
Location: Tucson, Arizona