Cast to int vs floor
Casting to an int will truncate toward zero. floor()
will truncate toward negative infinite. This will give you different values if bar
were negative.
Cast to int vs Math.floor
In this case both Case to Int and Math.floor will return integer value. If x=3.5 then both function will return 3 in output. Cast to int is a function to convert variable of any datatype to integer type, on the other hand Math.floor function will only floor the decimal number to integer not converting datatype. But result will be different in case of negative values because Cast to Int approaches to zero and Math.floor approaches to negative infinity. So in that perspective if you are working on real numbers (both positive and negative) then it is unsafe to use Cast to Int instead of Math.floor to get precise output.
Why does casting to int not floor all doubles in C
Because the value of the double was less than 2
double=1.99999999999999978
int=1
Try it but this time add some precision
#include <math.h>
#include <stdio.h>
int main(){
int i;
double f=log(2.0)/log(pow(2.0,1.0/2.0));
printf("double=%0.17f\n",f);
printf("int=%d\n",(int) f);
}
Confusing as hell the first time you experience it. Now, if you try this
#include <math.h>
#include <stdio.h>
int main(){
int i;
double f=log(2.0)/log(pow(2.0,1.0/2.0));
printf("double=%0.17f\n",f);
printf("int=%d\n",(int) f);
printf("int=%d\n", (int)round(f));
}
It will correctly round the value. If you look in the man page (on a mac at least) you'll see the following comment...
round, lround, llround -- round to integral value, regardless of rounding direction
What do they mean by direction, it's all specified in IEEE 754. If you check the different ways to round to an integer... floor is mentioned as rounding towards -ve infinity
which is in this case was towards 1
:)
What is the difference between int() and floor() in Python 3?
floor()
rounds down. int()
truncates. The difference is clear when you use negative numbers:
>>> import math
>>> math.floor(-3.5)
-4
>>> int(-3.5)
-3
Rounding down on negative numbers means that they move away from 0, truncating moves them closer to 0.
Putting it differently, the floor()
is always going to be lower or equal to the original. int()
is going to be closer to zero or equal.
Floor vs int cast difference
Floating point numbers have trouble rendering decimal places. It is more of an approximation.
2**-6 + 2**-7 + 2**-8 + 2**-9 + 2**-11 + 2**-13 + 2**-14 + 2**-15 + 2**-20 + 2**-22 + 2**-26
= 0.0299999863
Using binary, I drove the accuracy to 26 binary. I got close to 0.03 but not quite. In my example I chose to be under 0.03 but I could have gone a little above (i.e. 0.03000001. I don't think it is possible to represent 0.03 perfectly in floating point notation.
Multiplying 0.03 by any number produces yet another approximation. Casting to type int will cut out everything after the decimal place. I assume the implementation of floor is more elegant. Your compiler probably choose a floating point value of 32.99999 so and int would make 32.
floor() and ceil() functions vs casting to integer in C
The functions ceil()
and floor()
will return different numbers than what you get by using
up = (int)(test + 1);
down = (int)test;
when you have a negative number.
If you have:
float test = -1.3548;
up = (int)test; // ceil()
down = (int)(test-1); // floor()
Even the last statement is not a good way to compute floor()
when test
is an integral number.
Unless you want to deal with positive and negative numbers differently, and the special cases of when test
is integral number, you are better off using ceil()
and floor()
.
Math.Floor vs cast to an integral type in C#
There are some differences between casting to an integral type and using Math.Floor:
- When casting to an integral type, you'll end up with an integral type (obviously). So if you want to keep the number as a double, using Floor is easier.
- As a consequence of 1, casting will not work correctly if the given number is too large to be represented by the given integral type (a double can represent much larger numbers than a long).
- Floor rounds towards negative infinity. Casting rounds towards zero.
C: difference between (int)x and floor(x)?
One big difference is that of negative numbers; if you change myF
to -5.6
, then casting to an int returns -5
while floor(myF)
is -6
.
As to which is preferable, as a rule of thumb I'd say to only cast to an int if you know that's what you need -- and since you're asking here, chances are that you probably want floor
.
(Also note that with printf
formatting, %ld
is a long integer; a double is %lf
.)
Is there any benefit to using Math.Floor over explicit integer casting?
Yes, for negative numbers, this works in the opposite way.
Example (using Mono's C# interactive shell csharp
):
csharp> Math.Floor(-12.0d)
-12
csharp> Math.Floor(-12.5d)
-13
csharp> (int) -12.5
-12
(same for both Java/C#) and I guess most languages anyway.
Casting a floating-point number to an integer, is performed by throwing away the decimal part maintaining the integer part. The integer part of -12.5
is 12
. Thus negative numbers do a Math.Ceil
if converted to an int
.
Furthermore as @Matthew argues, a float
or double
can reach numbers like 1.023e23
(Avogadro's constant). Simply because the mantisse can't represent digits after the comma anymore. Numbers that are considered to be an integer anyway, but can't be represented by an int
. By performing a Math.floor
operation, nothing happens, but the value is still maintained. While conversion to an int
could result in overflow:
Example:
csharp> double ac = 1.023e23;
csharp> Math.Floor(ac);
1.023E+23
csharp> (int) ac;
0
Note: this may look far fetched, but there is thus a clear difference in semantics nevertheless. A difference that tends to lead to errors anyway.
In addition, it works differently for infinite numbers and NaN:
System.out.println(Math.floor(Double.POSITIVE_INFINITY)); // Prints Infinity
System.out.println((int)Double.POSITIVE_INFINITY); // Prints 2147483647
System.out.println(Math.floor(Double.NaN)); // Prints NaN
System.out.println((int)Double.NaN); // Prints 0
But I would always use them nevertheless. Casting makes things way more unreadable. Rounding up/down/off is more some kind of (side-effect) of the cast. By using Math.Ceil/Floor/Round
it is clear what you mean.
Sometimes a cast to an integer is indeed a bit more efficient than performing a floor/ceil operation first. But a smart compiler can sometimes derive that a variable will always store a positive number and thus optimize it itself. And furthermore for most applications this will result in an insignificant performance penalty.
PHP intval vs floor
The functions give different results with negative fractions.
echo floor(-0.1); // -1
echo intval(-0.1); // 0
Related Topics
Portability of Binary Serialization of Double/Float Type in C++
C++ New Operator Thread Safety in Linux and Gcc 4
Emulating Shifts on 32 Bytes with Avx
C++ Memory Model and Race Conditions on Char Arrays
Istream Behavior Change in C++ Upon Failure
How to Write to a Memory Buffer With a File*
Building Multiple Binaries Within One Eclipse Project
Operator Overloading in C++ as Int + Obj
Why Does Ostream_Iterator Not Work as Expected
Std::Optional Specialization for Reference Types
Check If Member Exists Using Enable_If
Standard Library Containers with Additional Optional Template Parameters
Child Process Receives Parent's Sigint
Cin for an Int Inputing a Char Causes Loop That Is Supposed to Check Input to Go Wild