[Tutor] Help with program
Mark Lawrence
breamoreboy at yahoo.co.uk
Mon Feb 16 19:45:38 CET 2015
On 16/02/2015 16:27, 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
Not that it matters but imports are usually done at the top of the module.
>
> 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? "))
*DON'T* use eval, it's potentially dangerous.
n = int(input("How many terms should be used? "))
x = float(input("What value should be used for x? "))
>
> s = 1
> d = 1
> e = 1
>
> value = 0
>
> for i in range(n - 1):
Are you aware that this will count from zero to n - 2?
> value = value + s + (x**e / math.factorial(d))
>
> s = s * 1
> e = e + 2
> d + d + 2
Whoops :)
> 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()
We'd usually write:-
if __name__ == "__main__":
main()
>
> Thank you!
>
> C.Skinner
--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.
Mark Lawrence
More information about the Tutor
mailing list