Hyperbolic cosine approach - Python

Asked

Viewed 113 times

1

I have a little exercise to do: compare the result of the Cosh(x) approximation by Taylor series with the function you have in the Python library.

The hyperbolic cosine Taylor series is:

Cosh(x) = 1 + x 2/2! + x 4/4! + x 6/6! + ... + x 2n/2n!

For now, I’ve made the code below:

import math

valores = raw_input().split(); n = int(valores[0]); x = float(valores[1])

def potencia(x, k):
    if k == 1:
        return x
    else:
        return x * potencia(x, k - 1)

def fatorial(k):
    if k == 0:
        return 1
    else:
        return k * fatorial(k - 1)

def main():
    i = 0
    soma = 0
    while i < n:
        soma = soma + ((potencia(x, 2 * i)) / fatorial(2 * i))
        i = i + 1
    print(n, " : %6.3f = %6.3f" %(soma, math.cosh(x)))

main()

And you keep making that mistake:

Traceback (most recent call last):
  File "coshx.py", line 25, in <module>
    main()
  File "coshx.py", line 21, in main
    soma = soma + ((potencia(x, 2 * i)) / fatorial(2 * i))
  File "coshx.py", line 9, in potencia
    return x * potencia(x, k - 1)

The last two lines of error repeat endlessly. What I’m doing wrong?

1 answer

3


The problem is that in the first iteration i Zero valley, then you end up calling potencia(x, 0). And that’s why the code always falls on else, making multiple recursive calls until the stack pops.

I mean, he’s gonna call potencia(x, -1), that falls in the else and flame potencia(x, -2), and so on. As never falls in the if, there is never a recursion return, and an hour the pile bursts.

But in your case it doesn’t have to be recursive. Nor does it need to calculate power and factorial from the beginning, because each term already has part of the calculation of the next. Then with each iteration do only the missing calculations.

For example, if I already have x2, I only need to multiply by x twice more to have x4. If I already have 2! then I just need to multiply by 3 and 4 to get 4! - then I just need to store the current power and factor value and multiply what is missing:

import math

n = # ler valor de n
x = # ler valor de x

soma = 0
potencia = fat = 1
for i in range(1, n + 1):
    soma += potencia / fat
    potencia *= x * x
    fat *= 2 * i * (2 * i - 1)

print(n, " : %6.3f = %6.3f" %(soma, math.cosh(x)))

See more about recursion reading here, here, here and here.

  • Thanks for the help, I realized what I was missing. I learned about recursion a short time ago, so I wanted to test some things.

Browser other questions tagged

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