I really could not understand your code, I found the variables' names very confusing, making it very difficult to understand what each thing is inside the code.
If you notice, the given sequence is the calculation of the sine function from the expansion by the Taylor series, given by the form:
Obviously,computationallyitwillbeimpossible(orinfeasible)toaddinfiniteterms,sowetakeafinitequantitythatiscloseenoughtothedesiredresult.Thisamountwillbedenotedby
n
:
Thevalueinsidethesummationiswhatwecallthegeneraltermoftheseriesandonlydependsonx
andi
,sowecandefineitinPython:
frommathimportfactorialdeftermo_geral(x,i):return((-1)**i/factorial(2*i+1))*(x**(2*i+1))
However,wemustcalculatethevaluefromthegeneraltermforeachvalueofi
from0ton-1
,sowecanassemblethesequence:
deftermos(x,n):foriinrange(n):yieldtermo_geral(x,i)
Andfinally,thesinecalculationwillbethesumofalltermsintheseries:
seno=sum(termos(x,n))
Sowecangeneralizethecalculationtoonlyonefunction:
frommathimportfactorial,radiansdefseno(x,n=7):x=radians(x)deftermo_geral(x,i):return((-1)**i/factorial(2*i+1))*(x**(2*i+1))deftermos(x,n):foriinrange(n):yieldtermo_geral(x,i)returnsum(termos(x,n))
Theinputofthefunctionmustbetheangleindegrees,justmakeseno(30)
togetthesineof30°.Atestthatthecodecorrectlycalculatestheseriesispresentedbelow,wherewecomputethevaluecalculatedbythedefinedfunctionandthenativefunctionofthemath
packagewithanerrorlessthan0.00001:
frommathimportradians,isclose,sinforanglein{0,30,45,60,90,120,180,230,270,320,360}:assertisclose(seno(angle,21),sin(radians(angle)),abs_tol=1e-5)
Seeworkingat Repl.it | Ideone | GitHub GIST
The absence of output indicates that all asserts have passed.