This question already has answers here:
Why does the division get rounded to an integer? [duplicate]
(13 answers)
Closed 4 years ago.
I'm solving some coding challenges on CoderByte and unfortunately they provide Python2. One thing I noticed is that the round() function is giving different outputs on python3 and python2. When i write this on python 2:
print int(round(100/60))
I get output of 1 (please explain why)
But on python 3 the same command gives 2 which is correct.
In python 2 the divide operator on integers returns integer, so 100/60==1. This unintuitive C-like behaviour was changed in python 3.
To make this code work properly in python 2 you should convert one of the integers to float: print int(round(100/60.)), that . means 60.0.
The problem is not the rounding, but the interpretation of /.
In python 2 if dividing 2 integers with / you get an integer not a float.
In python 3 you get a float if you use / - the "pure" integer division is done by using //.
Python 2:
print(100/60) # ==> 1
print(100/60.0) # ==> 1.6666666666...
Python 3:
print (100/60) # ==> 1.6666
print (100//60) # ==> 1
They both get rounded accordingly, but if you input a 1 into round, it will result in 1.
You can read more about the reason for the changed behaviour here: PEP 238
The current division (/) operator has an ambiguous meaning for numerical arguments: it returns the floor of the mathematical result of division if the arguments are ints or longs, but it returns a reasonable approximation of the division result if the arguments are floats or complex. This makes expressions expecting float or complex results error-prone when integers are not expected but possible as inputs.
We propose to fix this by introducing different operators for different operations: x/y to return a reasonable approximation of the mathematical result of the division ("true division"), x//y to return the floor ("floor division"). We call the current, mixed meaning of x/y "classic division".
Related
This question already has answers here:
Why does floating-point arithmetic not give exact results when adding decimal fractions?
(31 answers)
Closed 4 months ago.
a = [0.0021, 0.0087]
s = sum(a)
print(s)
Outcome: 0.010799999999999999
When executing the program above, the result is complex and eronated.
After performing multiple tests, including:
a = 0.0021
b = 0.0087
The result is the same. I tried different combinations of numbers and it seems that only these 2 have such an odd outcome.
I would say that this is floating point arithmetics error. Or I think there were some performance improvements done to math operations in Python which cause this, you can look more into it if you want by searching for PyNumber_Add and BINARY_ADD operation
This question already has answers here:
Python 3.x rounding behavior
(13 answers)
Closed 1 year ago.
I am using python 3.8.5 and rounding decimals and not floats which can behave strangely.
Python normally rounds all decimal.Decimals properly where .50 are rounded up.
However, only Decimal(1120.50) is rounding down. What could be the error in my code.
To recreate
import decimal
round(decimal.Decimal(1119.50))
# OK: Expected output 1120, actual output 1120
round(decimal.Decimal(1120.50))
# Wrong: Expected output 1121, actual output 1120
round(decimal.Decimal(1121.50))
# OK: Expected output 1122, actual output 1122
Any help would be appreciated.
Thanks
The round built-in function rounds towards the even solution when between two values.
This base round function definition is documented here: https://docs.python.org/3.7/library/functions.html#round
As the decimal package is a builtin, but not a basic type, it implements its own __round__ function, which follows the built-in standard of rounding to the even solution when between two values.
This isn't well documented, but I verified in the code itself: https://github.com/python/cpython/blob/1f0cde678406749524d11e852a16bf243cef5c5f/Lib/_pydecimal.py#L1890
There is no way to override the way the round function works for decimal objects.
Use quantize instead
The decimal package provides a function quantize which allows you to round and set the round type.
Quantize is documented here: https://docs.python.org/3/library/decimal.html#decimal.Decimal.quantize
and the round types are here: https://docs.python.org/3/library/decimal.html#rounding-modes
This question already has answers here:
How do I do exponentiation in python? [duplicate]
(3 answers)
Closed 2 years ago.
I am new to programming and just started a course and stuck on a demo section where I have to take a math calculation and program it in Python. When I program it do you follow BEDMAS order of figuring out or is there a logical order. The syntax is correct but I keep being told it is not right
See the equation below to be programmed into python. What are the rules for telling Python to calculate something correctly where 5 is the exponent
Use Python to calculate (((1+2)∗3)/4)5
Exponentiation in Python is done with the ** operator.
For instance:
2**8
is 256.
In Python to calculate exponent you use ** operator.
Similar to multiplication but double asterisk.
(((1+2)∗3)/4)**5
This will give you 32.
That is because you are using values which are all integers, so 9 / 4 will be 2, not 2.25.
Python has operator precedence that follows algebraic rules.
This question already has answers here:
How does Python implement the modulo operation?
(2 answers)
Modulo operator in Python [duplicate]
(5 answers)
Closed 3 years ago.
So I am implementing a custom hash function and I am not sure what kind of number and how big a number to choose. I have tried various prime numbers but I am not sure if % operator works faster for prime numbers. Actually, I am not sure if there are cases when modulo operator works faster or if there are any cases.
Maybe the answer lies within cython or some other low level implementation details?
From the Python online documentation:
The % (modulo) operator yields the remainder from the division of the
first argument by the second. The numeric arguments are first
converted to a common type. A zero right argument raises the
ZeroDivisionError exception. The arguments may be floating point
numbers, e.g., 3.14%0.7 equals 0.34 (since 3.14 equals 4*0.7 + 0.34.)
The modulo operator always yields a result with the same sign as its
second operand (or zero); the absolute value of the result is strictly
smaller than the absolute value of the second operand 1.
6. Expressions - Binary arithmetic operations - Modulo operator
A prime number ads no necessary improvement of degradation, the operator behaviour prevails.
If your looking to get the division and remainder in one go, you're looking for the divmod() function.
This question already has answers here:
Why does Python return 0 for simple division calculation?
(6 answers)
What is the difference between '/' and '//' when used for division?
(16 answers)
Closed 4 years ago.
I have a line of Python code that doesn't work the way it should (at least to the best of my knowledge). Following is the code line:
print 'progress: {}%'.format((i/len(e_numbers))*100)
The value of i starts from 0 and goes up to length of e_numbers which is a list, while the length of e_numbers is around 17000. But the code always prints Progress: 0%.
Any idea why?
In Python 2, using / to divide two integers performs integer division by default, rounding the result down to the nearest integer value. Thus, as long as i is between 0 and len(e_numbers), i/len(e_numbers) is going to be 0. There are two possible solutions:
Cast one or both operands to a float before dividing, e.g., float(i)/len(e_numbers)
Put from __future__ import division at the top of your file so that / always produces a float.