math expressions (see polynomials for more)
from Goulib.notebook import *
from Goulib.expr import *
from Goulib.table import Table
from math import pi,sin
from Goulib.math2 import sqrt
Expr can be created from:
Expr has LaTeX representation in notebooks
Expr(3**5) # is evaluated before Expr is created
e=Expr(3)**Expr(5) # combine Expr essions
h('as LaTeX (default) :',e)
print('as math formula :',e)
print('as python code :',repr(e))
print('evaluated :',e())
e=Expr('5**3+(-3^2)') # ^ and ** are both considered as power operator for clarity+compatibility
h('as LaTeX (default) :',e)
print('as math formula :',e)
print('as python code :',repr(e))
print('evaluated :',e())
e=Expr('x^2')
h('an Expr may contain variables :',e)
h('and be evaluated as a function : for x=2, ',e,'=',e(x=2))
all functions defined in math module can be used:
functions=default_context.functions # functions known by default to Expr
t=Table()
for n in functions:
f=functions[n][0] # get the function itself
try:
e=Expr(f)
t.append([n,repr(e),str(e),e])
except Exception as e:
t.append([n,e])
t
e=Expr(sqrt) #(Expr(pi))+Expr(1/5)
h('as LaTeX (default) :',e)
print('as math formula :',e)
print('as python code :',repr(e))
print('evaluated :',e())
e1=Expr('3*x+2') #a very simple expression defined from text
e1
e1=Expr(lambda x:3*x+2) #the same expression defined from a lambda function
e1
def f(x):
return 3*x+2
Expr(f) #the same expression defined from a regular (simple...) function
e3=Expr(sqrt)(e1) #Expr can be composed
e3
print(e3(x=1)) # Expr can be evaluated as a function
print(e3((pi-4)/6)) #the x variable is implicit
e1([-2,1,0,1,2]) # Expr can be evaluated at different x values at once
e3.plot() # Expr can be also plotted. Note the X axis is automatically restricted to the definition domain
Expr('1/x').plot(x=range(-100,100))
e=Expr('(-b+sqrt(b^2-4*a*c))/(2*a)') #laTex is rendered with some simple simplifications
e
e(a=1) # substitution doesn't work yet ...
e=Expr("e**(i*pi)")
e
e() # should be -1 one day...