Why does Python return 0 for simple division calculation?
In Python 2, 25/100
is zero when performing an integer divison. since the result is less than 1
.
You can "fix" this by adding from __future__ import division
to your script. This will always perform a float division when using the /
operator and use //
for integer division.
Another option would be making at least one of the operands a float, e.g. 25.0/100
.
In Python 3, 25/100
is always 0.25
.
Make division by zero equal to zero
Check if the denominator is zero before dividing. This avoids the overhead of catching the exception, which may be more efficient if you expect to be dividing by zero a lot.
def weird_division(n, d):
return n / d if d else 0
Why does the division get rounded to an integer?
You're using Python 2.x, where integer divisions will truncate instead of becoming a floating point number.
>>> 1 / 2
0
You should make one of them a float
:
>>> float(10 - 20) / (100 - 10)
-0.1111111111111111
or from __future__ import division
, which the forces /
to adopt Python 3.x's behavior that always returns a float.
>>> from __future__ import division
>>> (10 - 20) / (100 - 10)
-0.1111111111111111
BMI calculator always return 0. (Python)
Type cast it to float
. /
will do integer division always.
That is
bmi = float(weight) / float(length * length)
It will print
Weight in kg: 10
Length in cm: 20
0.025
Or do
from __future__ import division
How to return 0 with divide by zero
In numpy v1.7+, you can take advantage of the "where" option for ufuncs. You can do things in one line and you don't have to deal with the errstate context manager.
>>> a = np.array([-1, 0, 1, 2, 3], dtype=float)
>>> b = np.array([ 0, 0, 0, 2, 2], dtype=float)
# If you don't pass `out` the indices where (b == 0) will be uninitialized!
>>> c = np.divide(a, b, out=np.zeros_like(a), where=b!=0)
>>> print(c)
[ 0. 0. 0. 1. 1.5]
In this case, it does the divide calculation anywhere 'where' b does not equal zero. When b does equal zero, then it remains unchanged from whatever value you originally gave it in the 'out' argument.
How to return 0 with divide by 0 from string?
you can try
try:
#Your operation here
except ZeroDivisionError:
# return 0 here
More information here: https://en.wikibooks.org/wiki/Python_Programming/Exceptions
Returning math error (division by 0 etc) that otherwise crashes method
Wrap your statements with an try: except: else: block
Fx = input("what is the desired function of x?" )
listY = []
try:
for i in range(0,1001):
x = i/100
y = eval(Fx)
listY.append(y)
except ZeroDivisionError:
print("Divide by zero error for f({})".format(x))
except ValueError:
print("Invalid value for f({})".format(x))
else:
print("This function's minimum value is", min(listY))
print("This function's maximum value is", max(listY))
I'm not sure how you can define there was a min or a max when you have undefined results. You could use limits around the undefined result(s) to understand which direction you approached the undefined value.
But if you want to simply return the min or max of the values that were defined you can move the try block inside the for loop, e.g:
Fx = input("what is the desired function of x?" )
listY = []
undefined = False
for i in range(0,1001):
try:
x = i/100
y = eval(Fx)
except ZeroDivisionError:
print("Divide by zero error for f({})".format(x))
undefined = True
except ValueError:
print("Invalid value for f({})".format(x))
undefined = True
else:
listY.append(y)
if undefined:
print("Ignoring undefined results")
print("This function's minimum value is", min(listY))
print("This function's maximum value is", max(listY))
Related Topics
How to Set Environment Variables in Pycharm
Maximum Value for Long Integer
Replacing Few Values in a Pandas Dataframe Column with Another Value
List to Dictionary Conversion with Multiple Values Per Key
How to Make a Tkinter Window Jump to the Front
List Comprehension VS Generator Expression's Weird Timeit Results
Convert Pandas Dataframe to Nested JSON
How to Remove Nan Value While Combining Two Column in Panda Data Frame
Matplotlib Y Axis Values Are Not Ordered
Replace() Method Not Working on Pandas Dataframe
Df.Append() Is Not Appending to the Dataframe
Error When Configuring Tkinter Widget: 'Nonetype' Object Has No Attribute
How to Debug in Django, the Good Way