Posted on 25th July 2024|43 views
How to resolve math domain error in python?
I am getting this error when I am running this code
from numpy import zeros, array
from math import sin, log
from newtonRaphson2 import *
def f(y):
f = zeros(len(y))
f[0] = sin(y[0]) + y[1]**2 + log(y[2]) - 6.0
f[1] = 3.0*y[0] + 2.0**y[1] - y[2]**3 + 2.0
f[2] = y[0] + y[1] + y[2] -6.0
return f
y = array([1.0, 1.0, 1.0])
print newtonRaphson2(f,y)
Posted on 25th July 2024| views
The code is doing a log of a number which is less than or equal to zero, which is mathematically undefined, so the function gives you the error called math domain error, but you can use math.log1p(y) which returns the natural algorithm of 1+y(base e). The outcome is calculated in such a way that is accurate for y near zero. You can then convert back to the actual value using math.expm1 that returns e raised to the power y-1.