Understanding gduals and floats¶
(by Dario Izzo)
Arithmetic operators +,-,+,/ and ** work on a gdual as well as mathematical functions (from pyaudi). But not everything must be a gdual. You can operate between gduals and floats too, and between gdual having different truncation order.
Importing stuff¶
[1]:
from pyaudi import gdual_double as gdual
from pyaudi import sin, cos, tan
Arithmetic between floats and gduals¶
[2]:
x = gdual(1.2, "x", 3) # a gdual
y = 2.1 # a float
f = x + y # this will be a gdual
f
[2]:
\[ 3.3+{dx}+\mathcal{O}\left(4\right) \]
NOTE: the gdual f defined above only contains derivative infos w.r.t the variable “x”. You cannot make derivatives w.r.t “y” as y was not defined as a gdual
[3]:
def f(x,y):
return x*x+2*tan(x/(y+1))-sin(x)
xf = 2
yf = 3
x = gdual(2., "x", 3)
y = gdual(3., "y", 3)
print("The result is a float: {}".format(f(xf,yf)))
print("The result is a gdual (contains only derivatives w.r.t. x): {}".format(f(x,yf)))
print("The result is a gdual (contains derivatives w.r.t. x and y): {}".format(f(x,y)))
The result is a float: 4.183307552861899
The result is a gdual (contains only derivatives w.r.t. x): 4.18331+5.06537*dx+1.54332*dx**2-0.0437224*dx**3
The result is a gdual (contains derivatives w.r.t. x and y): -0.324612*dy+0.104137*dx*dy**2-0.0437224*dx**3+4.18331-0.250974*dx*dy-0.0345762*dy**3+5.06537*dx-0.0827871*dx**2*dy+0.10332*dy**2+1.54332*dx**2
Promoting a gdual¶
You can also perform arithmetic operations with gduals defined with a different differentiation order. In this case the resulting gdual will be “promoted” to the higher order
[4]:
x = gdual(0.1, "x", 2)
y = gdual(-2, "y", 4)
f = x+y
print(f)
print("Order: {}".format(f.order)) # The order is the maximum order terms will be retained during the
# computations using the truncated Taylor Polynomial algebra computations
print("Degree: {}".format(f.degree)) # The degree is the actual degree of the polynomial
#which will be less or equal than the order
-1.9+dy+dx
Order: 4
Degree: 1
NOTE: be careful when using gdual promotion. You may “lose” information implicitly if the order equals the degree.