Numerical Methods

Lecture 4a: Python classes

by: Tomasz RomaƄczukiewicz
web: th.if.uj.edu.pl/~trom/
rm B-2-03


Outline

  • Derivative
In [28]:
class A:
    u=3    

a = A()
a.w = 7
b = A()
b.w = 9
a.u = 4
print((a.u, a.w), (b.u, b.w))
(4, 7) (3, 9)
In [29]:
class B:
    def __init__(self, b):
        self.u=b

a = B(4)
a.w = 7
b = B(5)
b.w = 9
a.u = 4
print((a.u, a.w), (b.u, b.w))
(4, 7) (5, 9)
In [30]:
class Exact_derivative:
    def __init__(self, f, df):
        self.f = f
        self.df = df
    
    def __add__(self, other): 
        return Exact_derivative(self.f + other.f, self.df + other.df)
    
    def __mul__(self, other): 
        return Exact_derivative(self.f*other.f, self.df*other.f +  self.f*other.df)
     
    
    def __str__(self): 
        return "< {:g}, {:g} >".format(self.f, self.df)
    
X  = Exact_derivative(3, 1)
C = Exact_derivative(2, 0)
var_f = X*X+C# f=x^2+2, f'=2*x 
print(var_f)      # f=3^2+2, f'=2*3 
< 11, 6 >
In [31]:
import numpy as np

def Sin(F):
    return Exact_derivative(np.sin(F.f), np.cos(F.f)*F.df)

Res = Sin(X*X)
print(Res)  # < sin(x^2),  2*x*cos(x^2) >
x = 3
print("< {:f}, {:g} >".format(np.sin(x**2), 2*x*np.cos(x**2)))  # < sin(x^2),  2*x*cos(x^2) >
< 0.412118, -5.46678 >
< 0.412118, -5.46678 >
In [32]:
class Sym_derivative:
    def __init__(self, f, df):
        self.f = f
        self.df = df
    
    def __add__(self, other): 
        return Sym_derivative("({:s})+({:s})".format(self.f, other.f),
                              "({:s})+({:s})".format(self.df, other.df))
    
    def __mul__(self, other): 
        return Sym_derivative("({:s})*({:s})".format(self.f, other.f), 
                              "({:s})*({:s})+({:s})*({:s})".format(self.f, other.df, self.df, other.f))
    
    def __str__(self): 
        return "< {:s}, {:s} >".format(self.f, self.df)
    
var_x   = Sym_derivative("x", "1")
const_2 = Sym_derivative("2", "0")
var_f = var_x*var_x+const_2 # f=x^2+2, f'=2*x 
print(var_f)      # f=3^2+2, f'=2*3 
< ((x)*(x))+(2), ((x)*(1)+(1)*(x))+(0) >
In [33]:
g = lambda x: eval(var_f.f)
dg = lambda x: eval(var_f.df)

g(3), dg(3)
Out[33]:
(11, 6)
In [34]:
var_f.__dict__
Out[34]:
{'f': '((x)*(x))+(2)', 'df': '((x)*(1)+(1)*(x))+(0)'}
In [38]:
dir(var_f)
Out[38]:
['__add__',
 '__class__',
 '__delattr__',
 '__dict__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__le__',
 '__lt__',
 '__module__',
 '__mul__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '__weakref__',
 'df',
 'f']
In [36]:
Sin.__code__
Out[36]:
<code object Sin at 0x7f64ca507030, file "<ipython-input-31-0a058e9674bf>", line 3>