Advertisement
calcpage

2016Summary.py

Jun 23rd, 2016
1,248
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.74 KB | None | 0 0
  1. #!/usr/bin/python
  2. #MrG 2016.0624 Pythonic Calculus Executive Summary!
  3. from math import sqrt,pi
  4. from turtle import *
  5.  
  6. #1) define a function, ie f(x)=x**2-2
  7. def f(x):
  8.     return x**2-2
  9. print "f(sqrt(2)) = ", f(sqrt(2))
  10.  
  11. #2) find the numerical derivative as a limit
  12. def diff(x,h):
  13.     return (f(x+h)-f(x))/h
  14.  
  15. print
  16. print "f'(2) = "
  17. for x in range(5):
  18.     print diff(2,10**-x)
  19.  
  20. #3) find roots using newton's method as a limit
  21. def root(g):
  22.     return g-f(g)/diff(g,10**-6)
  23.  
  24. print
  25. print "the closest root of f(x)==0 near x=1 is:"
  26. g=1
  27. for x in range(5):
  28.     print g
  29.     g=root(g)
  30.  
  31. #4) find the definite integral as a limit
  32. print
  33. print "the definite integral of f(x) from 0 to pi ="
  34. a=float(0)
  35. b=pi
  36. for x in range(5):
  37.     n=10**x
  38.     h=(b-a)/n
  39.     l=sum([f(a+i*h)*h for i in range(n)])
  40.     r=l-f(a)*h+f(b)*h
  41.     print (l+r)/2
  42.    
  43. #5) plots using turtle.py package from idle
  44. #5) f(x)=x**2-2 ==> f(1)==-1
  45. #5) f'(x)=2*x ==> f'(1)==2
  46. #5) tangent line to f(x) at x=1 is:
  47. #5) y-y1==m*(x-x1) ==> y-f(x1)==f'(x1)*(x-x1)
  48. #5) y+1==2*(x-1) ==> y+1==2*x-2 ==> y=2*x-3
  49. def g(x):
  50.     return 2*x-3
  51.  
  52. def plot(size):
  53.     #canvas
  54.     setworldcoordinates(-size,-size,size,size)
  55.     #hide turtle
  56.     ht()
  57.     # x-axis
  58.     pu()
  59.     color("green")
  60.     setpos(-size,0)
  61.     pd()
  62.     fd(2*size)
  63.     # y-axis
  64.     pu()
  65.     color("green")
  66.     setpos(0,-size)
  67.     rt(270)
  68.     pd()
  69.     fd(2*size)
  70.     # plot f(x)
  71.     pu()
  72.     color("red")
  73.     setpos(-size,f(-size))
  74.     pd()
  75.     x=-size
  76.     while x <= size:
  77.         x+=0.1
  78.         goto(x,f(x))
  79.     # plot g(x)
  80.     pu()
  81.     color("blue")
  82.     setpos(-size,g(-size))
  83.     pd()
  84.     x=-size
  85.     while x <= size:
  86.         x+=0.1
  87.         goto(x,g(x))
  88.     #delay
  89.     mainloop()
  90.  
  91. plot(3)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement