[Tutor] Help with program
Peter Otten
__peter__ at web.de
Mon Feb 16 20:04:03 CET 2015
Courtney Skinner wrote:
> Hello,
>
> I am trying to build a program that approximates the value of cosine -
> this is my program so far. It is not returning the right values. Could you
> tell me what I am doing wrong?
>
>
> def main():
>
> import math
>
> print("This program approximates the cosine of x by summing")
> print("the terms of this series: x^0 / 0!, -x^2 / 2!,")
> print("x^4 / 4!, -x^6 / 6!...")
>
> n = eval(input("How many terms should be used? "))
> x = eval(input("What value should be used for x? "))
Consider the more restrictive int() and float() instead of eval().
> s = 1
A nice suggestive name like "sign" instead of "s" might help you with your
debugging efforts. Of course the same goes for your other names.
> d = 1
> e = 1
>
> value = 0
>
> for i in range(n - 1):
> value = value + s + (x**e / math.factorial(d))
With the name suggested above the error
value = value + sign + (x**e / math.factorial(d))
should almost be obvious. sign plus? wait what...
Add
print("current exponent", e)
to see another problem.
>
> s = s * 1
That shows signs of a missing sign ;)
> e = e + 2
> d + d + 2
>
>
>
> print("Approximation for cos(x) calculated by this program: ")
> print(value)
> print()
>
> difference = math.cos(x) - value
>
> print("Difference between this value and math.cos(x): ")
> print(difference)
>
> main()
>
> Thank you!
>
> C.Skinner
More information about the Tutor
mailing list