Python: 4/5=0.0. Float declaration missing? [duplicate] - python

This question already has answers here:
Why does the division get rounded to an integer? [duplicate]
(13 answers)
Closed 6 years ago.
Apologies if this has already been asked but why does this:
a=4
b=5
c=float(a/b)
print c
Gives
>>>>
0.0
rather than 0.8?

That's because this is an integer division:
>>> 4/5
0
if you want to get 0.8, cast one of the two to float before the division:
>>> 4/float(5)
0.8

In Python 2, division between 2 integers will return an integer (rounding to the closest integer to 0), in this case, 0. Your code is basically float(0) which is 0.0.
You would need to change one of your values to a float first if you want to return a float.
This behavior is changed in Python 3, where division between 2 integers will return a float, 0.8 in this case.

If you do not want to introduce float in one of the variables. You could do this:
from __future__ import division
4/5
This will give what you are looking for 0.8, without having to introduce floating.

In Python 2 / returns only integer part if you use two integers - like int(0.8). You have to use float ie. float(a) or 4.0 (shortly 4.) or * 1.0
print float(4)/5
print 4/float(5)
print 4.0/5
print 4/5.0
print 4./5
print 4/5.
print a*1.0/b # sometimes you can see this method
print a/(b*1.0) # this version need () - without () you get (a/b)*1.0

4/5 will return 0 because it's an int division, then you cast float on 0

Because of integer division....dividing two integers will return and integer. The value of 0.8 is truncated to 0.
You need to elevate one of your integers to a float if you want a floating point answer.
E.G.
c = float(a) / b

Related

i am trying to make a function that returns price excluding vat [duplicate]

This question already has answers here:
How can I force division to be floating point? Division keeps rounding down to 0?
(11 answers)
Closed 4 months ago.
I was trying to normalize a set of numbers from -100 to 0 to a range of 10-100 and was having problems only to notice that even with no variables at all, this does not evaluate the way I would expect it to:
>>> (20-10) / (100-10)
0
Float division doesn't work either:
>>> float((20-10) / (100-10))
0.0
If either side of the division is cast to a float it will work:
>>> (20-10) / float((100-10))
0.1111111111111111
Each side in the first example is evaluating as an int which means the final answer will be cast to an int. Since 0.111 is less than .5, it rounds to 0. It is not transparent in my opinion, but I guess that's the way it is.
What is the explanation?
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
You're putting Integers in so Python is giving you an integer back:
>>> 10 / 90
0
If if you cast this to a float afterwards the rounding will have already been done, in other words, 0 integer will always become 0 float.
If you use floats on either side of the division then Python will give you the answer you expect.
>>> 10 / 90.0
0.1111111111111111
So in your case:
>>> float(20-10) / (100-10)
0.1111111111111111
>>> (20-10) / float(100-10)
0.1111111111111111
In Python 2.7, the / operator is an integer division if inputs are integers:
>>>20/15
1
>>>20.0/15.0
1.33333333333
>>>20.0/15
1.33333333333
In Python 3.3, the / operator is a float division even if the inputs are integer.
>>> 20/15
1.33333333333
>>>20.0/15
1.33333333333
For integer division in Python 3, we will use the // operator.
The // operator is an integer division operator in both Python 2.7 and Python 3.3.
In Python 2.7 and Python 3.3:
>>>20//15
1
Now, see the comparison
>>>a = 7.0/4.0
>>>b = 7/4
>>>print a == b
For the above program, the output will be False in Python 2.7 and True in Python 3.3.
In Python 2.7 a = 1.75 and b = 1.
In Python 3.3 a = 1.75 and b = 1.75, just because / is a float division.
You need to change it to a float BEFORE you do the division. That is:
float(20 - 10) / (100 - 10)
It has to do with the version of python that you use. Basically it adopts the C behavior: if you divide two integers, the results will be rounded down to an integer. Also keep in mind that Python does the operations from left to right, which plays a role when you typecast.
Example:
Since this is a question that always pops in my head when I am doing arithmetic operations (should I convert to float and which number), an example from that aspect is presented:
>>> a = 1/2/3/4/5/4/3
>>> a
0
When we divide integers, not surprisingly it gets lower rounded.
>>> a = 1/2/3/4/5/4/float(3)
>>> a
0.0
If we typecast the last integer to float, we will still get zero, since by the time our number gets divided by the float has already become 0 because of the integer division.
>>> a = 1/2/3/float(4)/5/4/3
>>> a
0.0
Same scenario as above but shifting the float typecast a little closer to the left side.
>>> a = float(1)/2/3/4/5/4/3
>>> a
0.0006944444444444445
Finally, when we typecast the first integer to float, the result is the desired one, since beginning from the first division, i.e. the leftmost one, we use floats.
Extra 1: If you are trying to answer that to improve arithmetic evaluation, you should check this
Extra 2: Please be careful of the following scenario:
>>> a = float(1/2/3/4/5/4/3)
>>> a
0.0
Specifying a float by placing a '.' after the number will also cause it to default to float.
>>> 1 / 2
0
>>> 1. / 2.
0.5
Make at least one of them float, then it will be float division, not integer:
>>> (20.0-10) / (100-10)
0.1111111111111111
Casting the result to float is too late.
In python cv2 not updated the division calculation. so, you must include from __future__ import division in first line of the program.
Either way, it's integer division. 10/90 = 0. In the second case, you're merely casting 0 to a float.
Try casting one of the operands of "/" to be a float:
float(20-10) / (100-10)
You're casting to float after the division has already happened in your second example. Try this:
float(20-10) / float(100-10)
I'm somewhat surprised that no one has mentioned that the original poster might have liked rational numbers to result. Should you be interested in this, the Python-based program Sage has your back. (Currently still based on Python 2.x, though 3.x is under way.)
sage: (20-10) / (100-10)
1/9
This isn't a solution for everyone, because it does do some preparsing so these numbers aren't ints, but Sage Integer class elements. Still, worth mentioning as a part of the Python ecosystem.
Personally I preferred to insert a 1. * at the very beginning. So the expression become something like this:
1. * (20-10) / (100-10)
As I always do a division for some formula like:
accuracy = 1. * (len(y_val) - sum(y_val)) / len(y_val)
so it is impossible to simply add a .0 like 20.0. And in my case, wrapping with a float() may lose a little bit readability.
In Python 3, the “//” operator works as a floor division for integer and float arguments. However, the operator / returns a float value if one of the arguments is a float (this is similar to C++)
eg:
# A Python program to demonstrate the use of
# "//" for integers
print (5//2)
print (-5//2)
Output:
2
-3
# A Python program to demonstrate use of
# "/" for floating point numbers
print (5.0/2)
print (-5.0/2)
Output:
2.5
-2.5
ref: https://www.geeksforgeeks.org/division-operator-in-python/

Why does 2/5 evaluate to 0 and not 0.4 [duplicate]

This question already has answers here:
How can I force division to be floating point? Division keeps rounding down to 0?
(11 answers)
Closed 4 months ago.
I was trying to normalize a set of numbers from -100 to 0 to a range of 10-100 and was having problems only to notice that even with no variables at all, this does not evaluate the way I would expect it to:
>>> (20-10) / (100-10)
0
Float division doesn't work either:
>>> float((20-10) / (100-10))
0.0
If either side of the division is cast to a float it will work:
>>> (20-10) / float((100-10))
0.1111111111111111
Each side in the first example is evaluating as an int which means the final answer will be cast to an int. Since 0.111 is less than .5, it rounds to 0. It is not transparent in my opinion, but I guess that's the way it is.
What is the explanation?
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
You're putting Integers in so Python is giving you an integer back:
>>> 10 / 90
0
If if you cast this to a float afterwards the rounding will have already been done, in other words, 0 integer will always become 0 float.
If you use floats on either side of the division then Python will give you the answer you expect.
>>> 10 / 90.0
0.1111111111111111
So in your case:
>>> float(20-10) / (100-10)
0.1111111111111111
>>> (20-10) / float(100-10)
0.1111111111111111
In Python 2.7, the / operator is an integer division if inputs are integers:
>>>20/15
1
>>>20.0/15.0
1.33333333333
>>>20.0/15
1.33333333333
In Python 3.3, the / operator is a float division even if the inputs are integer.
>>> 20/15
1.33333333333
>>>20.0/15
1.33333333333
For integer division in Python 3, we will use the // operator.
The // operator is an integer division operator in both Python 2.7 and Python 3.3.
In Python 2.7 and Python 3.3:
>>>20//15
1
Now, see the comparison
>>>a = 7.0/4.0
>>>b = 7/4
>>>print a == b
For the above program, the output will be False in Python 2.7 and True in Python 3.3.
In Python 2.7 a = 1.75 and b = 1.
In Python 3.3 a = 1.75 and b = 1.75, just because / is a float division.
You need to change it to a float BEFORE you do the division. That is:
float(20 - 10) / (100 - 10)
It has to do with the version of python that you use. Basically it adopts the C behavior: if you divide two integers, the results will be rounded down to an integer. Also keep in mind that Python does the operations from left to right, which plays a role when you typecast.
Example:
Since this is a question that always pops in my head when I am doing arithmetic operations (should I convert to float and which number), an example from that aspect is presented:
>>> a = 1/2/3/4/5/4/3
>>> a
0
When we divide integers, not surprisingly it gets lower rounded.
>>> a = 1/2/3/4/5/4/float(3)
>>> a
0.0
If we typecast the last integer to float, we will still get zero, since by the time our number gets divided by the float has already become 0 because of the integer division.
>>> a = 1/2/3/float(4)/5/4/3
>>> a
0.0
Same scenario as above but shifting the float typecast a little closer to the left side.
>>> a = float(1)/2/3/4/5/4/3
>>> a
0.0006944444444444445
Finally, when we typecast the first integer to float, the result is the desired one, since beginning from the first division, i.e. the leftmost one, we use floats.
Extra 1: If you are trying to answer that to improve arithmetic evaluation, you should check this
Extra 2: Please be careful of the following scenario:
>>> a = float(1/2/3/4/5/4/3)
>>> a
0.0
Specifying a float by placing a '.' after the number will also cause it to default to float.
>>> 1 / 2
0
>>> 1. / 2.
0.5
Make at least one of them float, then it will be float division, not integer:
>>> (20.0-10) / (100-10)
0.1111111111111111
Casting the result to float is too late.
In python cv2 not updated the division calculation. so, you must include from __future__ import division in first line of the program.
Either way, it's integer division. 10/90 = 0. In the second case, you're merely casting 0 to a float.
Try casting one of the operands of "/" to be a float:
float(20-10) / (100-10)
You're casting to float after the division has already happened in your second example. Try this:
float(20-10) / float(100-10)
I'm somewhat surprised that no one has mentioned that the original poster might have liked rational numbers to result. Should you be interested in this, the Python-based program Sage has your back. (Currently still based on Python 2.x, though 3.x is under way.)
sage: (20-10) / (100-10)
1/9
This isn't a solution for everyone, because it does do some preparsing so these numbers aren't ints, but Sage Integer class elements. Still, worth mentioning as a part of the Python ecosystem.
Personally I preferred to insert a 1. * at the very beginning. So the expression become something like this:
1. * (20-10) / (100-10)
As I always do a division for some formula like:
accuracy = 1. * (len(y_val) - sum(y_val)) / len(y_val)
so it is impossible to simply add a .0 like 20.0. And in my case, wrapping with a float() may lose a little bit readability.
In Python 3, the “//” operator works as a floor division for integer and float arguments. However, the operator / returns a float value if one of the arguments is a float (this is similar to C++)
eg:
# A Python program to demonstrate the use of
# "//" for integers
print (5//2)
print (-5//2)
Output:
2
-3
# A Python program to demonstrate use of
# "/" for floating point numbers
print (5.0/2)
print (-5.0/2)
Output:
2.5
-2.5
ref: https://www.geeksforgeeks.org/division-operator-in-python/

I want to get rounded int number in python?

I have a number 120 and I divided by 100. I am getting 1.2 but actually I want to get 2 only (not 2.0) in python without importing any lib.
Can any one help here???
You can use the modulo operator to know whether to round up the result:
120//100 + (1 if 120%100 else 0)
You can use the built-in function ceil() to round 1.2 up to 2, and the built-in int function to cast it to an integer:
In [3]: int(ceil(120/100.0))
Out[3]: 2

How to convert float value to another float value with some specified precession using python? [duplicate]

This question already has answers here:
Python rounding error with float numbers [duplicate]
(2 answers)
Closed 8 years ago.
How to convert float value to another float value with some specified precision using python?
>>> a = 0.1
but actually value of a is
0.10000000000000001
But I need to convert a to 0.1 in float type.
It is not possible to have 0.1 exactly when using the float type, due to how numbers are stored internally. This offsite resources will hopefully explain the internals more easily.
Note that when you use the Python console it may look like you have 0.1 exactly but this is not true, as the code below shows
In [35]: a = 0.1
In [36]: print(a)
0.1 # Looks fine! But wait, let's print with 30 decimal places...
In [37]: print('{:.30f}'.format(a))
0.100000000000000005551115123126 # Uh oh.
This occurs because when printing in the console, only a certain number of decimal places are printed, and for 0.1 this number is such that where it starts to deviate from 0 is outside the range.
Python does have a Decimal package which can provide support for decimal numbers, as below
import decimal
a = decimal.Decimal('0.1')
print(a)
# 0.1
print('{:.30f}'.format(a))
# 0.100000000000000000000000000000
Note that I've constructed the Decimal object using the string '0.1' as opposed to the float 0.1. This is because if I had used the float then the Decimal object would have contained the same "errors" that the float has.
How about the round function: Round
You can use formate function with float and round function also
>>> a = float(format(0.10000000000000001, '.1f'))
>>> a
0.1
>>> round(0.10000000000000001,2)
0.1

Python pow ** results [duplicate]

This question already has answers here:
How can I force division to be floating point? Division keeps rounding down to 0?
(11 answers)
Closed 9 years ago.
Why the build-in operator in this example 4**(1/2) (which is a square root operation) returns as a result 1 and not 2 as it should be expected? If is not going to return an acceptable result it should rise an error, but Python continues working without any crash. At least in Python 2.7.4 64 bit distribution.
It also happens with the math function pow(4,1/2) which returns 1 with no errors.
Instead, when doing 4**(0.5) it returns as a result 2.0 which is correct, although it mixes integers and floats without any warnings. The same happens with pow.
Any explanation for this behaviors? Shall they be considered as bugs?
1/2 uses floor division, not floating point division, because both operands are integers:
>>> 1/2
0
Use floating point values, or use from __future__ import division to switch to the Python 3 behaviour where the / operator always uses floating point division:
>>> 1/2.0
0.5
>>> 4**(1/2.0)
2.0
>>> from __future__ import division
>>> 1/2
0.5
>>> 4**(1/2)
2.0
1/2 gives 0.5 as an answer but since it is an int/int it returns an int hence it truncates the .5 and returns 0. In order to get a float result, either of the numbers must be float . Hence you must do:
>>> 4 ** (1.0/2)
2.0
This works perfectly, you can also try this:
>>> math.pow(4,1.0/2)
2.0
or you can also try this:
>>> math.sqrt(4)
2.0

Categories