This question already has answers here:
C# is rounding down divisions by itself
(10 answers)
Closed 8 years ago.
I am working in Unity3D with C# and I get a weird result. Can anyone tell me why my code equals 0?
float A = 1 / 90;
The literals 1 and 90 are interpreted as an int. So integer division is used. After that the result is converted to a float.
In general C# will read all sequences (without decimal dot) of digits as an int. An int will be converted to a float if necessary. But before the assignment, that's not necessary. So all calculations in between are done as ints.
In other words, what you've written is:
float A = (float) ((int) 1)/((int) 90)
(made it explicit here, this is more or less what the compiler reads).
Now a division of two int's is processed such that it takes only the integral part into account. The integral part of 0.011111 is 0 thus zero.
If you however modify one of the literals to a floating point (1f, 1.0f, 90f,...) or both, this will work. Thus use one of these:
float A = 1/90.0f;
float A = 1.0f/90;
float A = 1.0f/90.0f;
In that case, floating point division will be performed. Which takes into account both parts.
etc.
Related
This question already has answers here:
Why does integer division in C# return an integer and not a float?
(8 answers)
Closed 3 years ago.
I am grabbing total RAM of a computer system and available RAM and trying to work out what percentage is available.
I am using the following code:
double percent = my.Info.AvailablePhysicalMemory / my.Info.TotalPhysicalMemory;
and have also tried:
decimal percent = my.Info.AvailablePhysicalMemory / my.Info.TotalPhysicalMemory;
I am sure it's an issue with the type but I am unsure why both methods give a result of 0.
The actual values are Total: 17072574464 and Available: 8746000384. The values come back from the system cast as ulong. So what does percent always equal 0? If I put the numbers in directly it works fine. Just can't use the ulong variables - hence why I am sure it's my lack of experience with types in C# that is the problem.
You are trying to divide an integer by an integer, which always rounds down. You need to convert to a floating point number before you divide; for example:
double percent = my.Info.AvailablePhysicalMemory * 1.0 / my.Info.TotalPhysicalMemory;
This question already has answers here:
Is floating point math broken?
(31 answers)
Rounding of float values
(2 answers)
Difference between decimal, float and double in .NET?
(18 answers)
Closed 4 years ago.
float ff = (float)31.15;
double dd = 31.15;
var frst = Math.Round(ff, 1, MidpointRounding.AwayFromZero);
var drst = Math.Round(dd, 1, MidpointRounding.AwayFromZero);
frst: 31.1
drst: 31.2
Can someone explain why?
Well, Math.Round wants double, not float, that's why
Math.Round(ff, 1, MidpointRounding.AwayFromZero);
equals to
Math.Round((double)ff, 1, MidpointRounding.AwayFromZero);
and if we inspect (double)ff value
Console.Write(((double)ff).ToString("R"));
we'll see round up errors in action
31.149999618530273
Finally, Math.Round(31.149999618530273, 1, MidpointRounding.AwayFromZero) == 31.1 as expected
In floating point, all numbers are represented internally as fractions where the denominator is a power of 2.
(This is a similar way to how decimals are actually fractions with power-of-10 denominators. So 31.15 is just a way of writing the fraction 3115/100)
In floating point, 31.15 must be represented internally as a binary number. The closest binary fraction is: 1111.1001001100110011001100110011001100110011001100110011001100...repeating
The 1100 recurs (repeats forever), and so the number will be truncated depending on whether it is stored in a double or a float. In a float it is truncated to 24 digits, and in a double to 53.
Exact: 1111.100100110011001100110011001100110011001100110011001100110011001100...forever
Float: 1111.10010011001100110011
Double: 1111.1001001100110011001100110011001100110011001100110
Therefore you can see that the double that this number converts to, is actually slightly larger than the float it converts to. So it is clear that it won't necessarily round to the same number, since it is not the same number to begin with.
This question already has answers here:
Division returns zero
(8 answers)
Closed 8 years ago.
Example:
Output when debugging: bVar= 0.0
What am I missing?
You are dividing integers, not floats.
Use float bVarianza = (499f/ 500f); instead.
Your expression is evaluated as
float x = (float) (int / int).
After your integers have been divided (which results in 0 because integers don't have a fractal part) the result is stored in your variable of type float, which adds the .0 fractal part.
You divide an int by an int, so the answer is truncated to an int. That is, the expression 499/500 is evaluated to 0. Then you store 0 in a float, so it becomes 0.0.
If instead you say 499F / 500, then the expression itself will be a float, and you'll get a fractional result.
According to MSDN :
The division rounds the result towards zero, and the absolute value of
the result is the largest possible integer that is less than the
absolute value of the quotient of the two operands. The result is zero
or positive when the two operands have the same sign and zero or
negative when the two operands have opposite signs.
So if you want to get a float as result, you should cast types like
float bVarianza = (float)499 / (float)500;
in the case when one of operands is Real number, you can only cast the result:
float bVarianza = (float)(499/500.0);
This question already has answers here:
C# Float expression: strange behavior when casting the result float to int
(8 answers)
Closed 10 years ago.
Trying to cast float to int but there's something missing
float submittedAmount = 0.51f;
int amount = (int)(submittedAmount * 100);
Why is the answer 50?
Because of floating point aritmethics, the multiplied value isn't exactly 51. When I tried now, *0.51f * 100* gave the result 50.9999990463257.
And when you parse 50.9999990463257 to and int, you surely get 50.
If you want calculations like this to be exact, you will have to use a type like decimal instead of float.
If you want to understand why, read the article I have linked below.
What Every Computer Scientist Should Know About Floating-Point Arithmetic
Try with
int amount = (int)(submittedAmount * 100.0);
When you write 0.51f is not exactly 0.51
Read this great article called What Every Computer Scientist Should Know About Floating-Point Arithmetic
Use Convert class. Otherwise the answer still will be 50.
var amount = Convert.ToInt32(submittedAmount * 100.0));
0.51f is actually 0.509999999999. because floating points are imprecise.
I would like to add that, do not use float for monetary calculations. Use decimal instead.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
.Net float to double conversion
I though I understood floating point but can someone explain the following
float f = 1.85847987E+9F;
double d = Convert.ToDouble(f);
d is now converted to a string as 1858479872.0. I'm assuming the extra 2 is because double cannot represent the floating point number exactly.
My question is why does it seem to be able to rerepsent the same number when assigned directly
double d = 1.85847987E+9;
and it is shown exactly as 185847987.0
Because double can, and float cannot represent 1.85847987E+9 precisely.
Why the compiler doesn't complains about "float f = 1.85847987E+9F;" if it cant represents it properly
As per C# specification, section 4.1.6 Floating point types
The floating-point operators, including the assignment operators, never produce exceptions.
The problem is not double but float. Float is limited to 32 bit, while double uses 64 bit for precision.
Because a float exists out of a sign, mantissa and exponent. See Jon Skeet's answer here how to extract those values.
For 1.85847987E+9F, the mantissa is 7259687 and the exponent is 8. Then mantissa << exponent equals 1858479872. Since the precision for a float is limited to 7 digits, the value of any digit beyond 7 digits depends on the implementation, not the input. You can test this easily by inputting 123456789F.