This question already has an answer here:
in the following snippet of go code I struggle to understand why the results are different:
func main() {
a := -0.2; b := -0.1;
fmt.Println(a+b)
//Outputs expected float value with rounding error : -0.30000000000000004
c := (-0.2)+(-0.1)
fmt.Println(c)
//Will ouput -0.3 (the actual exact constant).
}
What is happening exactly, does go somehow performs the c operation as constant instead of float64 operation when these constants are not used to instantiate floats? Full working version : https://play.golang.org/p/kUICDGFiMvf
Any insights would be appreciated, thanks.
</div>
i try to use java and the resule is
public class StringTest {
public static void main(String[] args) {
double a = -0.2;
double b = -0.1;
System.out.println(a + b);
// -0.30000000000000004
double c = a + b;
System.out.println(c);
// -0.30000000000000004
}
}
it seems that the any programming language that uses binary floating point numbers will have this problem. some language's Number type used IEEE754 standard to represent number. And what is IEEE-745 float ,you can see it.