[Tutor] Help with program

Alan Gauld alan.gauld at btinternet.com
Mon Feb 16 19:55:23 CET 2015


On 16/02/15 16:27, Courtney Skinner wrote:
> Hello,
>
> I am trying to build a program that approximates the value of cosine


> def main():
>
>      import math

Its usual to do the imports outside the function at the tyop of the 
file. Python doesn't actually care much but its 'standard practice'.

>      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(). Use int() for the first one and float()
for the second. eval() is a security hazard and potentially
dangerous.

>      s = 1
>      d = 1
>      e = 1
>      value = 0
>
>      for i in range(n - 1):
>          value = value + s + (x**e / math.factorial(d))

Your description says you subtract every second value (eg -x**2/2!)
You are adding them all. Also you are adding 1(s) every time, surely
you just want to add it the first time. In other words you
want value to start at 1 and the loop to iterate from 2-(n-1)?
You also want a sign multiplier which toggles between +/-1
Also you can get Python to do most the work for you by specifying
a third step-size argument to range:

...
for e in range(2, (n*2)+1, 2): #step by 2
    value += (x**e)/math.factorial(e) * sign
    ...

You no longer need any of the other increments or variables.

>          s = s * 1
>          e = e + 2
>          d + d + 2

>          print("Approximation for cos(x) calculated by this program: ")
>          print(value)
>          print()

You probably want all of these outside the loop.
You might like to add a print(value) though while you are debugging.

>
>          difference = math.cos(x) - value
>
>          print("Difference between this value and math.cos(x): ")
>          print(difference)


HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list