M.Papapetros
M.Papapetros

Reputation: 49

Python function-unexpected output

I have this Python function:

def main(n,x):
   g=0
   for i in range(1,n):
       g+=((-1)^i)*(x^(2*i+1))/(2*i+1)
   return g

print main(3,2)

and the output is -6, when I think it should be 86/15. Where is my mistake? I want to find the n-value of x-(x^3)/3+(x^5)/5+...

Upvotes: 0

Views: 98

Answers (2)

Bal Krishna Jha
Bal Krishna Jha

Reputation: 7206

If you want your answer in fraction you can use:

from fractions import Fraction
def main(n,x):
   g=0
   for i in range(n):
       g+=Fraction(((-1)**i)*(x**(2*i+1)),(2*i+1))
   return g

print main(3,2)

It gives output:

86/15

Upvotes: 0

Moses Koledoye
Moses Koledoye

Reputation: 78536

A few issues with your current solution:

  1. Your exponentiation operator should be ** not ^ which is XOR.

  2. You should start range from 0 not 1 (then first multiplier is -1**0 = 1)

  3. Change one of the numbers in the division to float, to avoid integer division in Python 2.


def main(n, x):
   g = 0
   for i in range(n):
       g += ((-1)**i) * (x**(2*i+1))/float(2*i+1)
   return g

Upvotes: 3

Related Questions