Divide one by factorial confusion [duplicate] - java

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.

Related

What is the difference between Truncated Division and Floored division?

I need theoretical answer using mathematical approach. Is there any mathematical difference between them and how do they make impact in programming languages.
According to Java terminology, the question of "Truncated Division" vs "Floored division" is best answered by the javadoc of RoundingMode:
DOWN
Rounding mode to round towards zero. Never increments the digit prior to a discarded fraction (i.e., truncates). Note that this rounding mode never increases the magnitude of the calculated value.
FLOOR
Rounding mode to round towards negative infinity. If the result is positive, behave as for RoundingMode.DOWN; if negative, behave as for RoundingMode.UP. Note that this rounding mode never increases the calculated value.
The Java division operator is defined by JLS §15.17.2. Division Operator /:
Integer division rounds toward 0.
That is why 5 / -3 result in -1.
You can also look at the definition of "Truncate" vs "Floor" on Wikipedia:
There are many ways of rounding a number y to an integer q The most common ones are:
round down (or take the floor, or round towards minus infinity): q is the largest integer that does not exceed y.
round up (or take the ceiling, or round towards plus infinity): q is the smallest integer that is not less than y.
round towards zero (or truncate, or round away from infinity): q is the integer part of y, without its fraction digits.
round away from zero (or round towards infinity): if y is an integer, q is y; else q is the integer that is closest to 0 and is such that y is between 0 and q.
round to nearest: q is the integer that is closest to y (see below for tie-breaking rules).
As you can see, Java and Wikipedia agrees on this definition:
Truncate: Round towards zero
Floor: Round towards minus/negative infinity
Note that Java and Wikipedia disagrees on what Round Down means.
You're dividing integers, so the result is going to be rounded to the nearest integer. Use floating point variables instead.
For example, the second part of your question, 1.0/2.0 = 0.5.

Signed right shift operator on negative operands

I'm reading Java spec. and here is written:
The value of n >> s is n right-shifted s bit positions with
sign-extension. The resulting value is floor(n / 2s). For non-negative
values of n, this is equivalent to truncating integer division, as
computed by the integer division operator /, by two to the power s.
So if I have the following:
27 >> 3 // 00011011 >> 3 = 00000011 = 3 = 27/8
the result is 3; in fact 27/8 = 3.375 and thus 3 is that value truncated.
But the spec say nothing when left operand is negative.
So if I have the following:
-50 >> 2 // 11001110 >> 2 = 11110011 = -13 != -50/4
the result is -13; but -50/4 = -12.5 and thus -13 is not that value truncated.
So what's the rounding system Java use when the left operand is a negative value?
Maybe ceil(n / 2s)?
The resulting value is floor(n / 2s).
Floor means round down: round towards negative infinity. This is not the same as truncation, i.e. removing the fractional part. Truncation would cause positive numbers to round down and negative numbers to round up.
The floor of -12.5 is -13.
Demo.
Generally speaking Java does not use a rounding system at all, it just shifts some bits. If you need floor or ceil then use floor or ceil and use bit-shift operators when you need them.

Not sure why programme returns an int

Ok so basic question here.
double test = 1/3 * 3.14;
I realize that you need to do (1.0/3) in order to get the actual double number. But what I am wondering is why. I would have thought that since you are multiplying by 3.14 this would make it a double.
So am I correct in thinking that whenever two values are used in an arithmetic equation, regardless of what is happening around them, if they are integers then you will get an integer value?
ie. x/y * z
while x is divided by y that is all that the programme cares about and if they are both integers you will get an integer value back? It is only when you multiply it by z (3.14) that it becomes a double.
Evaluation occurs from left to right when two operators have equal precedence. * and / have equal precedence.
1 / 3 * 3.14 evaluates 1 / 3 first. Both operands are int, the first operation is integer division, and the result is an int.
Next, result * 3.14 is evaluated. One operand is an int, the other operand is a double, and we have mixed types. Java does us a favor and casts the int to a double to preserve accuracy. Floating point division occurs, and the result is a double.
With operators of equal precedence, the associativity takes over. These operators / and * are left-associative, which means that the order of operations proceeds from left to right.
So, 1/3 happens first, and integer division happens before the 3.14 has a chance to promote them to doubles.
Because according to the rules of arithmetics, 1/3 is calculated first. Since it's 2 integers, it's an integer division, resulting in 0. Afterwards you have a double calculation, but the error has already happened.
My understanding is that this has to do with autoboxing in java. Java assumed that the 1/3 is dividing two ints so you'd get an int back (casted into a double).
If you did 1/3D, you'd get 0.33333333 back

Why dividing an integer by zero and type casting it to float results infinity?

I had already searched through different questions on this topic but not get a clear idea.
Check this code:
class Test{
public static void main(String[] s){
int a=5;
float b=(float)a/0;
System.out.print(b);
}
}
the output is Infinity. But the thing I'm not getting is a is an int and a/0 must throw an exception. So how can it show output Infinity?
The reason is that
(float)a/0;
is interpreted as
((float)a)/0;
and not
(float)(a/0);
so you actually are converting a to a float before doing the division, not doing an integer division and then converting the result.
Hope this helps!
You are not dividing an integer by zero. You're dividing a float by zero, because your expression is equivalent to:
float b=((float)a)/0;
If you force the division to occur with only integers instead, like in the following example, the expected ArithmeticException will be thrown.
float b=(float)(a/0);
All floating-point computations follow the IEEE 754 specification. In particular, there
are three special floating-point values to denote overflows and errors:
• Positive infinity
• Negative infinity
• NaN (not a number)
For example, the result of dividing a positive number by 0 is positive infinity. Computing
0/0 or the square root of a negative number yields NaN.
see also
CAUTION: Floating-point numbers are not suitable for financial
calculation in which roundoff errors cannot be tolerated. For example,
the command System.out.println(2.0 -
1.1) prints 0.8999999999999999, not 0.9 as you would expect. Such
roundoff errors are caused by the fact that floating-point numbers are
represented in the binary number system. There is no precise binary
representation of the fraction 1/10, just as there is no accurate
representation of the fraction 1/3 in the decimal system. If you need
precise numerical computations without roundoff errors, use the
BigDecimal class, which is introduced later in this chapter.
from core Java Volume 1 chapter 3
a is an int, except you cast it to a float at the time the division occurs. Note that the cast has higher precedence than division - with brackets for clarity it would be:
float b = ((float) a)/0;
So while a is an int, you're doing floating point division.
This is because Java doesn't allow division by zero with ints and it does with floating-point values.
Infinity is produced if a floating point operation creates such a large floating-point number that it cannot be represented normally.
The cast to float of a generates a automatic cast of 0 to float aswell
Because you're casting a to a float, then dividing by zero. Floats have +/- infinity.
http://www.velocityreviews.com/forums/t137207-division-by-zero-float-vs-int.html
The binary / operator performs division, producing the quotient of its operands. The left-hand operand is the dividend and the right-hand operand is the divisor.
Integer division rounds toward 0. That is, the quotient produced for operands n and d that are integers after binary numeric promotion (§5.6.2) is an integer value q whose magnitude is as large as possible while satisfying |d·q||n|; moreover, q is positive when |n||d| and n and d have the same sign, but q is negative when |n||d| and n and d have opposite signs. There is one special case that does not satisfy this rule: if the dividend is the negative integer of largest possible magnitude for its type, and the divisor is -1, then integer overflow occurs and the result is equal to the dividend. Despite the overflow, no exception is thrown in this case. On the other hand, if the value of the divisor in an integer division is 0, then an ArithmeticException is thrown.
The result of a floating-point division is determined by the specification of IEEE arithmetic:
If either operand is NaN, the result is NaN.
If the result is not NaN, the sign of the result is positive if both operands have the same sign, negative if the operands have different signs.
Division of an infinity by an infinity results in NaN.
Division of an infinity by a finite value results in a signed infinity. The sign is determined by the rule stated above.
Division of a finite value by an infinity results in a signed zero. The sign is determined by the rule stated above.
Division of a zero by a zero results in NaN; division of zero by any other finite value results in a signed zero. The sign is determined by the rule stated above.
Division of a nonzero finite value by a zero results in a signed infinity. The sign is determined by the rule stated above.
In the remaining cases, where neither an infinity nor NaN is involved, the exact mathematical quotient is computed. A floating-point value set is then chosen:
If the division expression is FP-strict (§15.4):
If the type of the division expression is float, then the float value set must be chosen.
If the type of the division expression is double, then the double value set must be chosen.
If the division expression is not FP-strict:
If the type of the division expression is float, then either the float value set or the float-extended-exponent value set may be chosen, at the whim of the implementation.
If the type of the division expression is double, then either the double value set or the double-extended-exponent value set may be chosen, at the whim of the implementation.
Next, a value must be chosen from the chosen value set to represent the quotient. If the magnitude of the quotient is too large to represent, we say the operation overflows; the result is then an infinity of appropriate sign. Otherwise, the quotient is rounded to the nearest value in the chosen value set using IEEE 754 round-to-nearest mode. The Java programming language requires support of gradual underflow as defined by IEEE 754 (§4.2.4).
Despite the fact that overflow, underflow, division by zero, or loss of information may occur, evaluation of a floating-point division operator / never throws a run-time exception.
This can be verified at: http://docs.oracle.com/javase/specs/jls/se5.0/html/expressions.html#15.17.2

How do I use modulus for float/double?

I'm creating an RPN calculator for a school project and having trouble with the modulus operator. Since we're using the double data type, modulus won't work on floating-point numbers. For example, 0.5 % 0.3 should return 0.2, but I'm getting a division by zero exception.
The instruction says to use fmod(). I've looked everywhere for fmod(), including javadoc, but I can't find it. I'm starting to think it's a method I'm going to have to create?
Edit: Hmmm, strange. I just plugged in those numbers again and it seems to be working fine… but just in case. Do I need to watch out for using the mod operator in Java when using floating types? I know something like this can't be done in C++ (I think).
You probably had a typo when you first ran it.
evaluating 0.5 % 0.3 returns '0.2' (A double) as expected.
Mindprod has a good overview of how modulus works in Java.
Unlike C, Java allows using the % for both integer and floating point and (unlike C89 and C++) it is well-defined for all inputs (including negatives):
From JLS §15.17.3:
The result of a floating-point
remainder operation is determined by
the rules of IEEE arithmetic:
If either operand is NaN, the result is NaN.
If the result is not NaN, the sign of the result equals the sign of
the dividend.
If the dividend is an infinity, or the divisor is a zero, or both, the
result is NaN.
If the dividend is finite and the divisor is an infinity, the result
equals the dividend.
If the dividend is a zero and the divisor is finite, the result
equals the dividend.
In the remaining cases, where neither an infinity, nor a zero, nor
NaN is involved, the floating-point
remainder r from the division of a
dividend n by a divisor d is defined
by the mathematical relation r=n-(d·q)
where q is an integer that is negative
only if n/d is negative and positive
only if n/d is positive, and whose
magnitude is as large as possible
without exceeding the magnitude of the
true mathematical quotient of n and d.
So for your example, 0.5/0.3 = 1.6... . q has the same sign (positive) as 0.5 (the dividend), and the magnitude is 1 (integer with largest magnitude not exceeding magnitude of 1.6...), and r = 0.5 - (0.3 * 1) = 0.2
I thought the regular modulus operator would work for this in Java, but it can't be hard to code. Just divide the numerator by the denominator, and take the integer portion of the result. Multiply that by the denominator, and subtract the result from the numerator.
x = n/d
xint = Integer portion of x
result = n - d*xint
fmod is the standard C function for handling floating-point modulus; I imagine your source was saying that Java handles floating-point modulus the same as C's fmod function. In Java you can use the % operator on doubles the same as on integers:
int x = 5 % 3; // x = 2
double y = .5 % .3; // y = .2

Categories