Advertisement
Guest User

Untitled

a guest
Feb 6th, 2016
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.58 KB | None | 0 0
  1. # Python lab 3 assignment 1
  2. #
  3.  
  4. ### Part 1 ###
  5.  
  6. # Define a function (using 'def') to calculate factorials
  7.  
  8. # Write a loop to print x and factorial(x) for x from 0 to 10 inclusive
  9.  
  10. def fact(x):
  11. result = 1
  12. if x == 0:
  13. result=1
  14. while x >0:
  15. result = result*x
  16. x = x - 1
  17. return result
  18.  
  19. def factorial():
  20. x = 0
  21. while 0 <= x <= 10:
  22. print x, fact(x)
  23. x = x + 1
  24. factorial()
  25.  
  26. #### Part 2 ####
  27.  
  28. # Write a function here called 'sin3terms' to calculate sin(x) using 3 terms
  29. # in the Taylor expansion
  30.  
  31. def sin3terms(x):
  32. y = x - (x**3)/fact(3) + (x**5)/fact(5)
  33.  
  34. return y
  35.  
  36.  
  37. # This loop will print the value of sin3terms from 0 to 2pi
  38. print "Part 2"
  39. pi = 3.141592653589793
  40. x = 0.0
  41. while x < 2*pi:
  42. print x, sin3terms(x)
  43. x = x + 0.1*pi
  44.  
  45.  
  46. #### Part 3 ####
  47.  
  48. # Write a function here called 'sinNterms' to calculate sin(x) using N terms
  49. # in the Taylor expansion. The first input should be the value of x, and the
  50. # second should be N.
  51.  
  52. def sinNterms(x,N):
  53. n = 1
  54. y = 0
  55. while n <= N:
  56. u = (x**(1+2(n-1))/fact(1+2(n+1))) * (-1)**(n+1)
  57. y = y + u
  58. n = n + 1
  59. return y
  60.  
  61. # This loop should print sin(2*pi) using from 1 to 9 terms
  62. print "Part 3"
  63. for i in range(1,10):
  64. print i, sinNterms(2*pi, i)
  65.  
  66. #### Part 4 ####
  67.  
  68. # Write a function "howManyTerms" to calculate the number of terms required
  69. # to calculate sin(x) to withtin an accuracy, a.
  70. # This imports the built-in "sin" function
  71. from math import *
  72.  
  73.  
  74. # Print out statements to answer questions 1 to 3:
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement