Post

PythonPython

r
ravi sankar

Posted on 27th February 2024|36 views

0
votes

Python Math Domain Error

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)

 

Answers
P
imran mohammad

Posted on 27th February 2024

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.

Write your answer

STILL GOT QUERIES?

Get a Live FREE Demo
  • Explore the trending and niche courses and learning maps
  • Learn about tuition fee, payment plans, and scholarships
  • Get access to webinars and self-paced learning videos