# floating point error or script engine error?

Hi, i am making some simulation game and my team found strange bug.
The simulation result of unity editor and window published exe is different.
And we found some floating point bug and we make some test code like below.
The result is different also.
I think script engine of unity3d editor have some serious bug about return value processing.

using UnityEngine;
using System.Collections;

public class FloatTest : MonoBehaviour {

``````string str = "";

float Func()
{
return 0.1f * 0.1f;
}

float Func1(float index)
{
return index * 0.1f;
}

// Use this for initialization
void Start () {
float test = Func();
float value = Func1(0.1f);

if( Func() == Func1(0.1f) )
{
str += "test1 same:";
}
else
{
str += "test1 differ:";
}

if( (float)Func() == (float)Func1(0.1f) )
{
str += "test2 same:";
}
else
{
str += "test2 differ:";
}

double r1 = Func ();
double r2 = Func1 (0.1f);

if( r1 == r2 )
{
str += "test3 same:";
}
else
{
str += "test3 differ:";
}

if(Func().Equals(Func1(0.1f)))
{
str += "Equals is true: ";
}
else
{
str += "Equals is false: ";
}
}

void OnGUI()
{
GUI.Label(new Rect(0, 0, 1000, 100), str);
}
``````

}

You don’t say what results you got, or what you were expecting, but all I see in your code is a lot of exact floating point comparisons - Func() == Func1(0.1f), r1 ==r2 etc.

Don’t ever make comparisons for equality of two floating point numbers - it’s not a bug in Unity - it’s just an inherent imprecision in how floating point maths works: Floating-point arithmetic - Wikipedia

Unity provides a Mathf.Approximately() function for this very reason.

Hi, dont use == sign for floats, as there might be so called magic numbers 1.000001 for example.
Instead use this Unity - Scripting API: Mathf.Approximately