calculus.py

Created by ews31415

Created on April 16, 2020

693 Bytes

Calculus, Derivative, Sum, Integral (Simpson’s Rule), Solve f(x) = 0 (Newton’s Method)


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

During your visit to our site, NumWorks needs to install "cookies" or use other technologies to collect data about you in order to:

With the exception of Cookies essential to the operation of the site, NumWorks leaves you the choice: you can accept Cookies for audience measurement by clicking on the "Accept and continue" button, or refuse these Cookies by clicking on the "Continue without accepting" button or by continuing your browsing. You can update your choice at any time by clicking on the link "Manage my cookies" at the bottom of the page. For more information, please consult our <a href="https://www.numworks.com/legal/cookies-policy/">cookies policy</a>.