Python function returning first value twice -


i've written function calculate sin(x) using taylor series specified degree of accuracy, 'n terms', problem results aren't being returned expected , can't figure out why, appreciated.

what expecting is: 1 6.28318530718 2 -35.0585169332 3 46.5467323429 4 -30.1591274102 5 11.8995665347 6 -3.19507604213 7 0.624876542716 8 -0.0932457590621 9 0.0109834031461

what getting is: 1 none 2 6.28318530718 3 -35.0585169332 4 46.5467323429 5 -30.1591274102 6 11.8995665347 7 -3.19507604213 8 0.624876542716 9 -0.0932457590621

thanks in advance.

def factorial(x):     if x <= 1:         return 1     else:         return x * factorial(x-1)  def sinnterms(x, n):     x = float(x)      while n >1:         result = x         in range(2, n):             power = ((2 * i)-1)             sign = 1             if % 2 == 0:                 sign = -1             else:                 sign = 1             result = result + (((x ** power)*sign) / factorial(power))         return result  pi = 3.141592653589793 in range(1,10):     print i, sinnterms(2*pi, i) 

i see putting return under break out of while loop. should explain if mean do. however, given for in range(1,10): means ignore first entry , return none when input argument 1. wanted? also, since exit after calculation, should not while n > 1 use if n > 1 avoid infinite recursion.

the reason why results off because using range incorrectly. range(2, n) gives list of numbers 2 n-1. range(2, 2) gives empty list.

you should calculate range(2, n+1)

def sinnterms(x, n):     x = float(x)      while n >1:         result = x         in range(2, n): 

your comment explains have lines of code in wrong order. should have

def sinnterms(x, n):     x = float(x)      result = x     # replace while if since not need loop     # otherwise infinite recursion     if n > 1:         in range(2, n+1):             power = ((2 * i)-1)             sign = 1             if % 2 == 0:                 sign = -1             # else not needed default             # else:             #     sign = 1             # use += operator calculation             result += (((x ** power)*sign) / factorial(power))     # return value indentation under if n > 1     return result 

note in order handle things set factorial return float not int.

an alternative method saves calculations is

def sinnterms(x, n):     x = float(x)     lim = 1e-12     result = 0     sign = 1     # range gives odd numbers, saves calculation.     in range(1, 2*(n+1), 2):         # use += operator calculation         temp = ((x ** i)*sign) / factorial(i)         if fabs(temp) < lim:             break         result += temp         sign *= -1     return result 

Comments

Popular posts from this blog

java - pagination of xlsx file to XSSFworkbook using apache POI -

Unlimited choices in BASH case statement -

apache - How do I stop my index.php being run twice for every user -