浮点精度 [英] Floating point accuracy
本文介绍了浮点精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在写一种方法来计算 a * x + b * y = 1
//给定两个点,通过求解两个线性方程来求出线的方程,然后测试结果。 (为简单起见,假设delta!= 0)
private boolean solveAndRetry(float x1,float y1,float x2,float y2){
float delta = x1 * y2 - x2 * Y1;
float deltaA = y2 - y1;
float deltaB = x1 - x2;
float a = deltaA / delta;
float b = deltaB / delta;
float c = 1;
// test
if(a * x2 + b * y2 == c){
System.out.println(ok);
返回true;
}
else {
System.out.println(a * x2 + b * y2-c);
返回false;
$ b当我运行它的时候,所有确定,但事实并非如此,我不知道为什么 public static void main(String [] (float x = 0; x <10; x + = 0.01f){
solveAndRetry(1,-1,x,2);
结果如下:
pre $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ ok
ok
-5.9604645E-8
ok
-5.9604645E-8
ok
ok
ok
1.1920929E -7
ok
ok
-5.9604645E-8
ok
float 的精确度为6到7位十进制数字。由于四舍五入的错误无法避免,所以你的结果是可以得到的。
通常,你永远不会比较浮点数的相等性。 $ b
> Math.abs(x-y) eps
为适当选择的eps。
I am writing a method which calculates the equation of a 2D Line in the form a*x+b*y=1
//Given two points, find the equation of the line by solving two linear equations and then test the result. (For simplicity, assume that delta !=0 here)
private boolean solveAndRetry(float x1,float y1, float x2,float y2) {
float delta = x1 * y2 - x2 * y1;
float deltaA = y2 - y1;
float deltaB = x1 - x2;
float a = deltaA / delta;
float b = deltaB / delta;
float c = 1;
//test
if (a * x2 + b * y2 == c) {
System.out.println("ok");
return true;
}
else {
System.out.println(a * x2 + b * y2-c);
return false;
}
}
When I ran it, I was expecting there would be all "ok"s, but that's not the case and I don't know why
public static void main(String[] args) {
for (float x = 0; x < 10; x += 0.01f) {
solveAndRetry(1, -1, x, 2);
}
}
Here are some lines in the result
ok
ok
ok
ok
ok
ok
ok
ok
-5.9604645E-8
ok
-5.9604645E-8
ok
ok
ok
1.1920929E-7
ok
ok
-5.9604645E-8
ok
解决方案 A float
has an accuracy of 6 to 7 decimal digits. Since rounding errors cannot be avoided, your results are as good as it can get.
Normally, you would never compare floating point numbers for equality. Instead of x == y
always use a comparison with an interval:
Math.abs(x - y) < eps
for a suitably chosen eps.
这篇关于浮点精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文