Error divide by zero encountered in double_scalars in Python
Hello guys, I'm newbie in Python and I created a short function help caculate float number for me, you can see as below:
import numpy as np
def float_number(x):
x = np.float_(x)
y = int(input("Input large number: "))
return 10.7 / (5. - x)
print ('Float function with value 5 = ', odd_even(5.))
I use float_ fuction of numpy package to help convert number integer to float, but when run app it throw an exception main.py:6: RuntimeWarning: divide by zero encountered in double_scalars.
Input large number: 12
main.py:6: RuntimeWarning: divide by zero encountered in double_scalars
return 10.7 / (5. - x)
Float function with value 5 = inf
I understand that 10.7 / 0 with throw exception, but I really don't know any solution to solve it.
I'm using Python 3.9 and window 10.
Thankyou for any solution for me.
-
A0
Alexis Nidegger Dec 03 2021
You can check parameter before calculate and return data. You can check if x value equal 5 will return 0;
See example below:
import numpy as np def float_number(x): if x == 5: return 0; x = np.float_(x) y = int(input("Input large number: ")) return 10.7 / (5. - x) print ('Float function with value 5 = ', float_number(6.))
#Output
Float function with value 5 = 0
I hope it is a best solution for you.
-
D0
Deepak M Dec 03 2021
You need check value input before divide, as below:
def float_number(x): if (5. - x) == 0: return 0; x = np.float_(x) y = int(input("Input large number: ")) return 10.7 / (5. - x)
And it fixed for you, exception will not throw again.
* Type maximum 2000 characters.
* All comments have to wait approved before display.
* Please polite comment and respect questions and answers of others.