Sunday, May 24, 2020

Numworks/Casio MicroPython/Python: Calculus

Numworks/Casio MicroPython/Python:  Calculus 

Introduction

The following scripts creates the user functions for calculus:

f(x):  define your function in terms of x here.   This needs to be loaded into the script before running it.   Each of the functions that follow will use f(x).  You can call f(x) to evaluate the function at any value.

deriv(x):  The approximate derivative at point x.  The Five Stencil approximation is used. 

sigma(a,b):  Calculate the sum  (Σ f(x)) from x = a to x = b. 

integral(a,b,n):  Calculates the definite integral ( ∫ f(x) dx) from x = a to x = b.  The Simpson's rule is used with n divisions (n needs to be even)

solve(x0):  Uses Newton's Rule to find roots for f(x). 

Example

f(x) = -2x*^2 + 3x + 5
In Python:  -2*x**2+3*x+5

f(0): 5
f(10): -165
f(-10): -225

deriv(10): -37.00004450971999

Σ f(x): x = 1 to 25:  sigma(1,25): -8780

∫ f(x) dx: x = -3 to 1, n = 20:  integral(-3,1,20):  -10.666666666667

Solve f(x)=0, initial condition x0 = 2.5:  solve(5):  2.5 

Python Script: calculus.py

from math import *

# 2020-04-15 EWS

# define f(x) here
def f(x):
  return -2*x**2+3*x+5
  
# derivative
def deriv(x):
  # uses f(x), 5 stencil
  # h is tolerance
  h=1e-10
  d=(12*h)**-1*(f(x-2*h)-8*f(x-h)+8*f(x+h)-f(x+2*h))
  return d

# sum/sigma
def sigma(a,b):
  t=0
  n=b-a
  for i in range(n):
    t=t+f(i+1)
  return t

# integral by simpsons rule
def integral(a,b,n):
  t=f(a)+f(b)
  h=(b-a)/n
  for i in range(n-1):
    w=(i+1)/2
    if (w-int(w))==0:
      t=t+2*f(a+(i+1)*h)
    else:
      t=t+4*f(a+(i+1)*h)
  t=t*h/3
  return t

# solver
def solve(x0):
  tol=1e-14
  x1=x0-f(x0)/deriv(x0)
  while abs(x1-x0)>tol:
    x0=x1
    x1=x0-f(x0)/deriv(x0)
  return x1


Eddie

All original content copyright, © 2011-2020.  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.