This question already has answers here:
Negative integer division surprising result
(5 answers)
Why is -1/2 evaluated to 0 in C++, but -1 in Python?
(4 answers)
Closed last month.
I found that -1 // 2 is equal to -1 (Why not 0?), but int(-1 / 2) is equal to 0 (as I expected).
It's not the case with 1 instead of -1, so both 1 // 2 and int(1 / 2) is equal to 0.
Why the results are different for -1?
In Python, the division operator / and the floor division operator // have different behavior.
The division operator / returns a floating-point number that represents the exact quotient of the division. In the case of -1/2, the quotient is -0.5. When you cast it to int, it rounds the number up to 0.
The floor division operator // returns the quotient of the division rounded down to the nearest integer. In the case of -1//2, the quotient is -1, because -1 divided by 2 is -0.5, which is rounded down to -1.
That's why -1//2 = -1 and int(-1/2) = 0 in python.
Related
For example,
int result;
result = 125/100;
or
result = 43/100;
Will result always be the floor of the division? What is the defined behavior?
Will result always be the floor of the division? What is the defined behavior?
Not quite. It rounds toward 0, rather than flooring.
6.5.5 Multiplicative operators
6 When integers are divided, the result of the / operator is the algebraic quotient with any
fractional part discarded.88) If the quotient a/b is representable, the expression
(a/b)*b + a%b shall equal a.
and the corresponding footnote:
This is often called ‘‘truncation toward zero’’.
Of course two points to note are:
3 The usual arithmetic conversions are performed on the operands.
and:
5 The result of the / operator is the
quotient from the division of the
first operand by the second; the
result of the % operator is the
remainder. In both operations, if the
value of the second operand is zero,
the behavior is undefined.
[Note: Emphasis mine]
Dirkgently gives an excellent description of integer division in C99, but you should also know that in C89 integer division with a negative operand has an implementation-defined direction.
From the ANSI C draft (3.3.5):
If either operand is negative, whether the result of the / operator is the largest integer less than the algebraic quotient or the smallest integer greater than the algebraic quotient is implementation-defined, as is the sign of the result of the % operator. If the quotient a/b is representable, the expression (a/b)*b + a%b shall equal a.
So watch out with negative numbers when you are stuck with a C89 compiler.
It's a fun fact that C99 chose truncation towards zero because that was how FORTRAN did it. See this message on comp.std.c.
Yes, the result is always truncated towards zero. It will round towards the smallest absolute value.
-5 / 2 = -2
5 / 2 = 2
For unsigned and non-negative signed values, this is the same as floor (rounding towards -Infinity).
Where the result is negative, C truncates towards 0 rather than flooring - I learnt this reading about why Python integer division always floors here: Why Python's Integer Division Floors
Will result always be the floor of the division?
No. The result varies, but variation happens only for negative values.
What is the defined behavior?
To make it clear floor rounds towards negative infinity,while integer division rounds towards zero (truncates)
For positive values they are the same
int integerDivisionResultPositive= 125/100;//= 1
double flooringResultPositive= floor(125.0/100.0);//=1.0
For negative value this is different
int integerDivisionResultNegative= -125/100;//=-1
double flooringResultNegative= floor(-125.0/100.0);//=-2.0
I know people have answered your question but in layman terms:
5 / 2 = 2 //since both 5 and 2 are integers and integers division always truncates decimals
5.0 / 2 or 5 / 2.0 or 5.0 /2.0 = 2.5 //here either 5 or 2 or both has decimal hence the quotient you will get will be in decimal.
This question already has answers here:
Why does Python's modulus operator (%) not match the Euclidean definition?
(1 answer)
Floor division with negative number
(4 answers)
Closed 3 years ago.
In my mind, the answer should be -1. Because 3//2 is equal to 1. Can someone explain why my console outputs -2?
value = -3//2
print(value)
I'm assuming this is python and // is integer division
In python integer division // rounds down (left on the number line) to the nearest integer
-3/2 outputs a float -1.5 not integer division so no rounding
-3//2 outputs an integer -2 rounds down(left) to the nearest integer on the number line
If this is python, then // is known as floor division, and it is an operator that rounds the result down to the nearest whole number.
Therefore
-3/2 = -1,5 rounded down to the nearest whole number is equal to -2.
Therefore:
-3//2 = -2.
Given that the red line is where -1,5 is, by rounding down (this means moving always left in the axis) the closest number is -2, which is what the operator does. It does not round to the closest number to 0, because that would mean it is rounding up, since it would be moving right in the axis.
The modulo function in OCaml mod return results different when compared with the modulo operator in python.
OCaml:
# -1 mod 4
- : int = -1
Python:
>>> -1 % 4
3
Why are the result different?.
Is there any standard module function that operate as % in OCaml?.
Python is a bit different in its usage of the % operator, which really computes the modulo of two values, whereas other programming languages compute the remainder with the same operator. For example, the distinction is clear in Scheme:
(modulo -1 4) ; modulo
=> 3
(remainder -1 4) ; remainder
=> -1
In Python:
-1 % 4 # modulo
=> 3
math.fmod(-1, 4) # remainder
=> -1
But in OCaml, there's only mod (which computes the integer remainder), according to this table and as stated in the documentation:
-1 mod 4 (* remainder *)
=> -1
Of course, you can implement your own modulo operation in terms of remainder, like this:
let modulo x y =
let result = x mod y in
if result >= 0 then result
else result + y
The semantics of modulo are linked with the semantics of integer division (generally, if Q is the result of integer division a / b, and R is the result of a mod b, then a = Q * b + R must always be true), so different methods of rounding the result of integer division to an integer will produce different results for modulo.
The Wikipedia article Modulo operation has a very extensive table about how different languages handle modulo. There are a few common ways:
In languages like C, Java, OCaml, and many others, integer division rounds towards 0, which causes the result of modulo to always have the same sign as the dividend. In this case, the dividend (-1) is negative, so the modulo is also negative (-1).
In languages like Python, Ruby, and many others, integer division always rounds down (towards negative infinity), which causes the result of modulo to always have the same sign as the divisor. In this case, the divisor (4) is positive, so the modulo is also positive (3).
The expression 6 // 4 yields 1, where floor division produces the whole number after dividing a number.
But with a negative number, why does -6 // 4 return -2?
The // operator explicitly floors the result. Quoting the Binary arithmetic operations documentation:
the result is that of mathematical division with the ‘floor’ function applied to the result.
Flooring is not the same thing as rounding to 0; flooring always moves to the lower integer value. See the math.floor() function:
Return the floor of x, the largest integer less than or equal to x.
For -6 // 4, first the result of -6 / 4 is calculated, so -1.5. Flooring then moves to the lower integer value, so -2.
If you want to round towards zero instead, you'll have to do so explicitly; you could do this with the int() function on true division:
>>> int(-6 / 4)
-1
int() removes the decimal portion, so always rounds towards zero instead.
Floor division will also round down to the next lowest number, not the next lowest absolute value.
6 // 4 = 1.5, which rounds down to 1, and up to 2.
-6 // 4 = -1.5, which rounds down to -2, and up to -1.
// in Python is a "floor division" operator. That means that the result of such division is the floor of the result of regular division (performed with / operator).
The floor of the given number is the biggest integer smaller than the this number. For example
7 / 2 = 3.5 so 7 // 2 = floor of 3.5 = 3.
For negative numbers it is less intuitive: -7 / 2 = -3.5, so -7 // 2 = floor of -3.5 = -4. Similarly -1 // 10 = floor of -0.1 = -1.
// is defined to do the same thing as math.floor(): return the largest integer value less than or equal to the floating-point result. Zero is not less than or equal to -0.1.
A useful way to understand why floor division // yields the results it does for negative values is to consider that it complements the modulo, or remainder, % operator, which in Python is defined to always return a non-negative number.
5/3 is equivalent to 1 remainder 2
i.e.
5//3 = 1
5%3 = 2
But
-5/3 = -2
-5%3 = 1
Or
-2 + 1/3rd which is -1.6667 (ish)
It can seem strange, but it ensures results such as
-2,-2,-2,-1,-1,-1,0,0,0,1,1,1,2,2,2,3,3,3 etc. when generating sequences.
The python 2.6 docs state that x % y is defined as the remainder of x / y (http://docs.python.org/library/stdtypes.html#numeric-types-int-float-long-complex). I am not clear on what is really occurring though, as:
for i in range(2, 11):
print 1.0 % i
prints "1.0" ten times, rather than "0.5, 0.333333, 0.25" etc. as I expected (1/2 = 0.5, etc).
Modulo is performed in the integer context, not fractional (remainders are integers). Therefore:
1 % 1 = 0 (1 times 1 plus 0)
1 % 2 = 1 (2 times 0 plus 1)
1 % 3 = 1 (3 times 0 plus 1)
6 % 3 = 0 (3 times 2 plus 0)
7 % 3 = 1 (3 times 2 plus 1)
8 % 3 = 2 (3 times 2 plus 2)
etc
How do I get the actual remainder of x / y?
By that I presume you mean doing a regular floating point division?
for i in range(2, 11):
print 1.0 / i
I think you can get the result you want by doing something like this:
for i in range(2, 11):
print 1.0*(1 % i) / i
This computes the (integer) remainder as explained by others. Then you divide by the denominator again, to produce the fractional part of the quotient.
Note that I multiply the result of the modulo operation by 1.0 to ensure that a floating point division operation is done (rather than integer division, which will result in 0).
You've confused division and modulus.
"0.5, 0.333333, 0.25" etc. as I expected (1/2 = 0.5, etc)."
That's the result of division.
Not modulus.
Modulus (%) is the remainder left over after integer division.
Your sample values are simple division, which is the / operator. Not the % operator.
Wouldn't dividing 1 by an number larger than it result in 0 with remainder 1?
The number theorists in the crowd may correct me, but I think modulus/remainder is defined only on integers.
We can have 2 types of division, that we can define through the return types:
Float: a/b. For example: 3/2=1.5
def division(a,b):
return a/b
Int: a//b and a%b. For example: 3//2=1 and 3%2=1
def quotient(a,b):
return a//b
def remainder(a,b):
return a%b