Wednesday, August 3, 2022

Python - Lambda Week: Derivatives and Newton's Method

Python - Lambda Week: Derivatives and Newton's Method



Welcome to Python Week!  This we we're going to cover calculus and the keyword lambda.


Note:  All Python scripts presented this week were created using a TI-NSpire CX II CAS.   As of June 2022, the lambda keyword is available on all calculators (in the United States) that have Python.   If you are not sure, please check your calculator manual. 


Derivative


The Five Stencil Method is used.  Due to the approximate nature, results are rounded to 5 digits.


f'(x) ≈ (-f(x+2*h) + 8*f(x+h) - 8*f(x-h) + f(x-2*h)) / (12 * h)


h is set to 0.0001 to allow for a wide range of functions and to hopefully prevent float point overflows or underflows.  You can modify h or have the user input a value if you so wish.  


derivlam.py:  Derivative Using the Five Stencil Method


# Math Calculations

#================================

from math import *

#================================


print("The math module is imported.")

f=eval("lambda x:"+input("f(x)? "))


# input x0

x=eval(input("d/dx at x0: "))

h=.0001


# derivative, 5 stencil

d=(-f(x+2*h)+8*f(x+h)-8*f(x-h)+f(x-2*h))/(12*h)

print("round to 5 decimal points")

print("d/dx = "+str(round(d,5)))


Newton's Method


The next script finds the root of f(x) (solve f(x) = 0) with a guess.  


x_n+1 = x_n - f(x_n) / f'(x_n)


The derivative is calculated using the Five Stencil Method.   


I put a limit of 100 iterations because Newton's Method is not always perfect nor this script finds solutions in the complex plane, just the real numbers.  


newtonlam.py


# Math Calculations

#================================

from math import *

#================================

print("The math module is imported.")

print("Solve f(x)=0 to 6 places")

f=eval("lambda x:"+input("f(x)? "))


# input x0

x=eval(input("Guess? "))

h=.0001


w=1

n=1

while fabs(w)>10**(-7):

  d=(-f(x+2*h)+8*f(x+h)-8*f(x-h)+f(x-2*h))/(12*h)

  w=f(x)/d

  x-=w

  n+=1

  if n>100:

    print("iterations exceeded")

    break


if n<101:

  print("x = "+str(round(x,6)))

  print("iterations used: "+str(n))



All original content copyright, © 2011-2022.  Edward Shore.   Unauthorized use and/or unauthorized distribution for commercial purposes without express and written permission from the author is strictly prohibited.  This blog entry may be distributed for noncommercial purposes, provided that full credit is given to the author. 


  Casio fx-7000G vs Casio fx-CG 50: A Comparison of Generating Statistical Graphs Today’s blog entry is a comparison of how a hist...