How can i calculate these in python??
A = (x**1/1!) - (x**3/3!) (x**5/5!) - ... - (x**51/51!)
B = 1 - (x**2/2!) (x**4/4!) - ... - (x**50/50!)
I tried this code for calculating A and B but
A^2 B^2 ~= 1
but i get 2.xxxxxxxxx
def factorial(n):
fac = 1
for i in range(2, n 1):
fac *= i
return fac
def calcA(x):
c = True
A = 0
for i in range(1, 51, 2):
if c:
A = (x**i)/factorial(i)
else:
A -= (x**i)/factorial(i)
c = not c
return A
def calcB(x):
B = 1
c = False
for i in range(2, 50, 2):
if c:
B = (x**i)/factorial(i)
else:
B -= (x**i)/factorial(i)
c = not c
return B
I tried this but output is not correct
it should be almost 1
CodePudding user response:
Might as well use the factorial function from the math module. It will be faster than doing it in pure Python.
You can also restructure the code to be more concise by using cycle from itertools as follows:
from math import factorial as FACTORIAL
from operator import sub as SUB, add as ADD
from itertools import cycle as CYCLE
def calcA(x):
A = 0
func = CYCLE((ADD, SUB))
for i in range(1, 52, 2):
A = next(func)(A, x**i/FACTORIAL(i))
return A
def calcB(x):
B = 1
func = CYCLE((SUB, ADD))
for i in range(2, 51, 2):
B = next(func)(B, x**i/FACTORIAL(i))
return B
print(calcA(2)**2 calcB(2)**2)
Output:
1.0000000000000002
Note:
float precision is such that upper range limits of 24 (for A) and 23 (for B) will produce the same result
CodePudding user response:
Note that this:
for i in range(10):
print(i)
will print 0, 1, 2, 3, 4, ..., 9
. Not 10!
Similar for range(1, 51, 2)
it will start with 1
then 3
and stop at 49
.
Change your ranges into: range(1, 53, 2)
and range(2, 52, 2)
and you will get approximately 1