Float calculation errors - c#

in C#
float ratio = 185 / srcRect.Width;
where srcRect.Width = 400
returns 0 where it should return 0.45...
min value for float is -3.40282347E+38 so how is this possible?

You are performing an integer division and hence 185/srcRect.Width will return 0. You will need to change the expression to
float ratio = 185.0f / srcRect.Width;

185 is an integer literal, and so the division performed is integer division.
To perform a float division, use 185.0 or 185.0f instead (the former is a double, the latter is float)

The "f" or "d" suffixes may be added to literal numbers to turn them into floats or doubles respectively.
Like so:
float ratio = 185f / srcRect.Width;
note that "185.0" is actually a double unless it also has the "f" suffix.

Related

Division of Integer Parameters Returning Non Float Value

I have two Integer Parameters,I divide these parameters and store the result to a Float Variable.
float kx=(float)(img.Width / refsize.Width);
Taking an instance of the problem where
img.width=2620 refsize.width=1499
The kx variable should return ~1.747831887925284 by normal math.
But it keeps rounding it to an integer kx=1
Why is this happening?
This comes down to the order of operations
float kx=(float)(img.Width / refsize.Width);
first evaluates
img.Width / refsize.Width
then casts the result (which is the integer 1) to a float.
To get your expected result, cast both widths to a float before division (technically you can cast either one and the compiler will promote the other, but I prefer to be explicit. You never know who will maintain the code years down the road).
float kx=(float)img.Width / (float)refsize.Width;
float kx=(img.Width / (float)refsize.Width);
It happens because you divide two ints and the result is int which you cast to float
It happens because you first divide integer by an integer which is integer or (DivideByZeroException). And then you convert integer result to float.
Try float kx = (((float)img.Width)/refsize.Width);
Since parentheses have priority, you have integer divided by integer and you get result 1. You should write
float kx = (float)img.Width / (float)refsize.Width;
to get the right result.

Why is c#'s precision for float.MaxValue more than it lets on?

C# code:
double value = float.MaxValue;
Console.WriteLine(value / 2);
give different values (C# gives 1.70141173319264E+38 and C# without floats gives me 1.701411735e+38) me .
When I use the c# code:
double value = 3.40282347E+38;
Console.WriteLine(value / 2);
I get the same as floats. Is MSDN wrong?
Dot Net Fiddle
float.MaxValue is 3.40282347E+38.
Float MaxValue
Fiddling around I found that
Console.WriteLine(((3.40282347E+38 / 2) == (float.MaxValue / 2)).ToString()); prints False while Console.WriteLine(((3.40282347E+38f / 2) == (float.MaxValue / 2)).ToString()); prints True. It's because the language does this:
By default, a real numeric literal on the right side of the assignment operator is treated as double.
Your number is a double and you are comparing it against a float, so the precision is different by default. You have to force the number to be a float by adding f on the end of it.

Why does this result in 0 and upsidedown not?

Currently I am writing my thesis and I was confronted with a behavior of .Net C# that I had never seen before. I am talking about an error in a calculation.
I implemented this formula:
1/2 * (Theta i-1 + Theta i) + Sum(Alph k, k=1, i-1)
This formula is applied to 4 objects. Theta is in all objects declared as float with the value 1,5708. Alpha is initialized with 0 and will be increased by each iteration.
First implmentation
float alpha = 0;
float value = 0;
for (int sphereCount = 1; sphereCount < this.spheres.Count; sphereCount++)
{
value = (1/2) * (this.spheres[sphereCount - 1].Theta + this.spheres[sphereCount].Theta);
alpha += value;
}
With this version value is always 0.0!
So I changed it to:
Working implementaion
float alpha = 0;
float value = 0;
for (int sphereCount = 1; sphereCount < this.spheres.Count; sphereCount++)
{
value =(this.spheres[sphereCount - 1].Theta + this.spheres[sphereCount].Theta) * 1/2;
alpha += value;
}
By removing the brackets around the 1/2 and placing it at the end of the calculation it worked.
WHY IS THAT SO???
It seems when you place 1/2 in brackets not depending on the position of 1/2 the result is 0.0. But also when i place (1/2) at the end it results in 0.0.
Does anyone here have an idea why?
This
(1 / 2)
evaluates to 0 because it's integer division. If you say
(1 / 2f)
or
(1 / (float) 2)
you'll be fine because it forces float divsion. Or, even better, just write 0.5.
If you write 1/2 the result is calculated using integer division that gives an integer result. You can force a floating point division by changing one of the numbers to a floating point number, as in 1/2f.
Or you could just write 0.5 which IMHO is more readable than 1/2.
Why multiply by 1? Rather than this:
value =(this.spheres[sphereCount - 1].Theta + this.spheres[sphereCount].Theta) * 1/2;
why not write this:
value =(this.spheres[sphereCount - 1].Theta + this.spheres[sphereCount].Theta) / 2;
You should write 1.0/2 or 0.5 instead 1/2.
1/2 is an integer division which results in an integer 0.
Because 1/2 is treated as integer arithmetic and as such is rounded to 0.
Removing the parenthesis changes the order of operations, and now you are dividing your whole (floating point) formula by two and arriving at a floating point answer.
That's because 1 and 2 are integer values, not floating point values.
When you divide the integer value 1 by the integer value 2, the result is the integer value 0, not the floating point value 0.5.
When you remove the parentheses and change the order of the multiplication, the other part of the expression will first be multiplied by 1, which will implicitly convert the integer value 1 into a floating point value. Then the result is divided by 2, which will also be implicitly converted into a floating point value.
So what you end up doing is:
value = ( (this.spheres[sphereCount - 1].Theta + this.spheres[sphereCount].Theta) * (float)1 ) / (float)2;

Is it safe to multiply a float/double by 0.5 instead of divide by 2 in C# and C++?

Basically for things like this (not real code):
for(int i = 0; i < 1000000000; ++i)
{
Vert v0 = mesh.polygons[i].edges[0].vert0;
Vert v1 = mesh.polygons[i].edges[0].vert1;
Vector3 center = (v0.pos + v1.pos) / 2;
}
v0.pos is of type Vector3<float, float, float>, but could be Vector3<double, double, double>.
Is it safe to just do?:
Vector3 center = (v0.pos + v1.pos) * 0.5;
This might seem like premature optimization but this has to be as fast as possible that will be called on billions of points (point clouds).
Not a C++ expert by any means, but in C#, doing this:
var a = new Func<float, float, double>((float f1, float f2) => (f1 + f2) * 0.5);
var b = new Func<float, float, double>((float f1, float f2) => (f1 + f2) / 2);
generates IL that in the former:
Loads the arguments
Adds them (producing a single)
Converts the result to a double
Loads the double argument (0.5)
Multiplies (producing a double)
Returns the result
and the latter
Loads the arguments
Adds them (producing a single)
Loads the constant integer (2)
Divides (producing a single, because single / integer produces a single)
Converts the result to a double
Returns the result
It strikes me that the former will likely have higher precision because the multiplication is performed on 2 doubles, resulting in double precision, whereas in the latter the division is performed on a single which is upcast to a double (but still only will have the precision of the single).
This bears me out:
Console.Out.WriteLine(((double)1) * ((double)1/3));
Console.Out.WriteLine((1) / ((float)3));
produces:
0.333333333333333
0.3333333
So, 'safe', maybe, if losing precision gaining extra precision is ok.

Annoying double value

Ok can anyone explain why the variable offset comes back as 0?
I need to update a progress bar but the value is less than 100 so offset is the value to increase current by and then update the progress bar with the floored value of current but as it comes back 0 it's not updating!
double offset = 0.000001;
int hmm = (image.Height * image.Width);
double current = 0;
MessageBox.Show(offset.ToString());
MessageBox.Show(hmm.ToString());
offset = 100 / hmm;// 0.01;// 100 / (image.Height * image.Width) * 10000;
MessageBox.Show(offset.ToString());
You're performing integer division - both hmm and 100 are integers. Therefore if hmm is greater than 100, it will always give 0 as the result. Convert either operand to a double and it'll use floating point arithmetic. For example:
double offset = 100.0 / hmm;
try using
offset = 100./hmm;
The problem is you're using integer division.
You are performing an integer division between 100 and hmm. The result would always be an integer, and you are seeing it produce 0 because hmm is greater than 100 in your case.
Try this instead:
offset = 100f / hmm; // the trailing f makes 100 a float
The problem is the last line of code. If you write 100 / hmm the result will be seen as integer value as 100 is an integer. Try using
((double)100)/hmm;
Integer division always drops the decimal point. Therefore, something like 1 / 100 = .01 would just become 0.
hmm is an int. Try declaring it as a float or double, or cast it as such when you perform the calculation.
IE.
offset = 100 / ((double)hmm);

Categories

Resources