Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations MikeeOK on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

NUnit??? 2

Status
Not open for further replies.

ajikoe

Programmer
Apr 16, 2004
71
ID
Hello I use NUnit for testing, but I found something wierd:

Assert.AreEqual(0.1,Math.Abs(2.1-2));//TRUE
Assert.AreEqual(true,Math.Abs(2.1-2)==0.1);//FALSE

Can anyone explain it?

Sincerely Yours,
Pujo
 
0.1 cannot be precisely represented in floating point (remember, everything is stored internally as binary), so you always get rounding errors. So comparing exact floating-point values will occasionally give you results like this.

I haven't seen any perfect way of handling this -- primarily, you should try not to floating point comparisons using the equality operator.

One method would be to decide on a level of accuracy, and test the value to see if you're within that range.
Code:
float Tolerance = 0.001;
float Value1 = 0.1;
float Value2 = 0.1;

if ((Value1 + Tolerance > Value2) && (Value1 - Tolerance < Value2))
{
   // Value1 is close enough to call it being equal
   // to Value2
}
Chip H.


____________________________________________________________________
If you want to get the best response to a question, please read FAQ222-2244 first
 
Same result just a little different
Code:
float Tolerance = 000.1f;
float Float1 = 0.1f;
float Float2 = 0.1f;
if (Math.Abs(Float1 - Float2) > Tolerance)
{
    Console.WriteLine("not equal");
}
Marty
 
You can apply the solutions recommended in the above posts but you should use Single.Epsilon , Double.Epsilon in such cases.
In the example below you will see the action of the Epsilon:
Code:
{
		float x1=(float)1/3;
		float x2=(float)0.33333333333;
		if (Math.Abs(x1-x2)<Single.Epsilon)
		{
			Console.WriteLine("Float Are equal");
		}
		else
		{
			Console.WriteLine("Float Are not equal");
		}
	}
	{
		double x1=(double)1/3;
		double x2=(double)0.33333333333;
		if (Math.Abs(x1-x2)<Double.Epsilon)
		{
			Console.WriteLine("Double Are equal");
		}
		else
		{
			Console.WriteLine("Double Are not equal");
		}
	}
The results are:
Float Are equal
Double Are not equal
obislavu
 
Thanks, obislavu. I had forgotten about that static constant.

Chip H.


____________________________________________________________________
If you want to get the best response to a question, please read FAQ222-2244 first
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top