Python Taylor series with no angle and error margin

Asked

Viewed 3,159 times

1

Hello! I need to assemble a program that calculates sine, cosine and exponential Taylor series in Python, but the program cannot accept an angle value, only x, number of series terms and an acceptable error. I tried to do this but it goes wrong because the values do not match what should give. the statement is this:

Consider the functions below:

sen(x) = x/1! - X3/3! + X5/5! - . . + (-1)k . x2k+1/(2k+1)! + . . .

cos(x) = 1 - x2/2! + X4/4! - X6/6! + . . + (-1)k . x2k/(2k)! + . . .

ex = 1 + x + x2/2! + X3/3! + X4/4! + ... + Xn/n! + ...

There are two ways to approach: 1. Calculate the sum of a number of terms. The greater the quantity of terms, the better the approximation. 2. Calculate the sum until you find a term whose absolute value is very small, because from a certain term, the following will always be lower in absolute value.

Your program should calculate the value of the above functions using the two approximation methods for various values of n (number of terms) and eps (very small value). You should also compare the calculated values to the one obtained using the existing function in the Python Math module.

thank you!! :)

def serie():

For the sine function

def sen():
    import math

    x = float(input("Entre com o valor de x: "))
    n = int(input("Entre com o valor de n, sendo ele positivo: "))
    eps = float(input("Entre com um valor bem pequeno: "))

    while n <= 0:
        n = int(input("Entre com um valor positivo de n: "))

    while eps <= 0 or eps >1:
        eps = float(input("Entre com um valor bem pequeno: "))

    seno = math.sin(x)
    print("O seno vale", seno)


    #Para calcular o seno com base na soma de termos
    sen_n = 0
    sinal_n = 0
    fat_n = 1

    for k in range (1, n + 1 ,2):
        fat_n = 1

        for i in range (2, k + 1):
            fat_n = fat_n * i

        sen_n += (pow(-1, sinal_n) * pow(x, k)) / fat_n
        sinal_n += 1
        sen1 = sen_n

    print("sen1 vale", sen1)

    print("A diferença pelo método 1 é", abs(sen1 - seno))

    sen()
serie()
  • Please take a look at my answer, and see what is missing - I would like to understand the question of the margin of error and then edit it if possible.

2 answers

1

I’d like to understand what it means k in the statement, and also on the error (I’m terrible at math). If you haven’t solved this question yet, I’ll keep your comments here.

That said, you can make the sums of terms of Taylor series, so:

# Primeiro fazemos a conversão para radianos
def para_radianos(x):
    return x/180*math.pi

# aqui nós fazemos a divisão e o fatorial
def taylor(x, i):
return math.pow(x, i)/math.factorial(i)

And now we need to do the sequence of sums and subtractions, for that, we create a loop:

# para o cálculo do seno
def calcula_seno(x, termos): # recebe o ângulo e no. de termos
    y = 3
    z = 0
    while True: # só para quando alcançarmos o número de termos
        z = z - taylor(x, y)
        y = y + 2
        z = z + taylor(x, y)
        y = y + 2
        if y >= termos: # alcançamos?
            break
    return x+z

And we call function that way:

angulo = 32
radianos = para_radianos(angulo)
calcula_seno(radianos, 1)

For the cosine calculation, the function is not very different from this one. Here is a complete example:

import math

# rad
def para_radianos(x):
    return x/180*math.pi

# taylor
def taylor(x, i):
    return math.pow(x, i)/math.factorial(i)

# sen
def calcula_seno(x, termos):
    y = 3
    z = 0
    while True:
        z = z - taylor(x, y)
        y = y + 2
        z = z + taylor(x, y)
        y = y + 2
        if y >= termos:
            break
    return x+z

# cos
def calcula_cosseno(x, termos):
    y = 2
    z = 0
    while True:
        z = z - taylor(x, y)
        y = y + 2
        z = z + taylor(x, y)
        y = y + 2
        if y >= termos:
            break
    return 1+z

# testa seno
print('testa seno:')
seno_math = math.sin(para_radianos(32))
seno_taylor = calcula_seno(para_radianos(32), 5)
print('math.sin: ' + str(seno_math))
print('taylor:   ' + str(seno_taylor))
print('')
# testa cosseno
print('testa cosseno:')
cosseno_math = math.cos(para_radianos(45))
cosseno_taylor = calcula_cosseno(para_radianos(45), 5)
print('math.sin: ' + str(cosseno_math))
print('taylor:   ' + str(cosseno_taylor))

Upshot: resultado da execução do programa

0


Your duties

sen(x) = x/1! – x3/3! + x5/5! - ... + (-1)k . x2k+1/(2k+1)! + ...
cos(x) = 1 – x2/2! + x4/4! – x6/6! + ... + (-1)k . x2k/(2k)! + ...
ex(x) = 1 + x + x2/2! + x3/3! + x4/4! + ... + xn/n! + ...

can be generalized to

f(y) = ∑ fn(n) / fd(n)! × y^(fe(n)) 

that is (taking the first 5 terms):

import math
def taylor(fn,fd,fe,x,iter=5):
  s=0
  for i in range(0, iter):
    s +=  fn(i)/math.factorial(fd(i))*math.pow(x, fe(i))
  return s

def seno(x):
  return taylor(lambda n: (-1)**n,
                lambda n: 2*n +1,
                lambda n: 2*n +1, x)

def cosseno(x):
  return taylor(lambda n: (-1)**n, 
                lambda n: 2*n,
                lambda n: 2*n, x)

def exp(x): return taylor(lambda n:1, lambda n:n, lambda n:n, x)

For testing...

def rad(x): return x/180*math.pi

r=rad(31)
print(math.sin(r), seno(r), math.sin(r)-seno(r))
## 0.5150380749100542 0.5150380749391384 -2.90842905315003e-11

Now add the various termination or error strategies

Browser other questions tagged

You are not signed in. Login or sign up in order to post.