Calculate the sine by Taylor series expansion

-2

Write a program that calculates an approximation for the sine according to the equation below:

seno(x) = x - x^3/3! + x^5/5! - x^7/7! + ... + x^n/n!

Since x and n are integers entered by the user. If n is even the program should report "n invalid".

I was able to write this:

x=int(input(">"))
n=int(input(">"))
fat=1
n00=1
n0=1
n01=1
d=0
s=0

if n%2==0:
    print("n inválido")
else:
    while n0<=n:
        while n01<=n0:
            fat=fat*n01
            n01=n01+1
        d=(x**n0)/fat
        s=d-s
        n0=n0+2
    print(s)

The calculation works, but in module. I know there are simpler ways, but I would like to fix it without changing too much.

    
asked by anonymous 22.09.2018 / 00:54

1 answer

5

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.Thisamountwillbedenotedbyn:

Thevalueinsidethesummationiswhatwecallthegeneraltermoftheseriesandonlydependsonxandi,sowecandefineitinPython:

frommathimportfactorialdeftermo_geral(x,i):return((-1)**i/factorial(2*i+1))*(x**(2*i+1))

However,wemustcalculatethevaluefromthegeneraltermforeachvalueofifrom0ton-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,wherewecomputethevaluecalculatedbythedefinedfunctionandthenativefunctionofthemathpackagewithanerrorlessthan0.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.

    
24.09.2018 / 18:30