Java测试编号的精度

时间:2011-10-25 09:16:31

标签: java precision epsilon


我必须编写一个方法,在不使用Math.atan()的情况下计算ArcTan 我的algorythm正在运作,但它并没有停止。

public final static double EPSILON = 1E-16; // Given Value 0,00000000000000010000
public static void main(String[] args)
{   
    double arcTan = formula;

    while(Math.abs(arcTan) < EPSILON)
    {
       ...myAlgorythm...    
    }
}

在23次循环后,我的algorythm计算出与Math.atan()几乎相同的arcTan,但我的时间并没有停止。
我如何以正确的方式规定停止条件?
为了更好的解释,请参阅我的循环输出:

1:  0,45833333333333330000  0,00000000000000010000
2:  0,46458333333333330000  0,00000000000000010000
3:  0,46346726190476184000  0,00000000000000010000
4:  0,46368427579365074000  0,00000000000000010000
5:  0,46363988658910527000  0,00000000000000010000
6:  0,46364927661314370000  0,00000000000000010000
7:  0,46364724210793534000  0,00000000000000010000
8:  0,46364769089584895000  0,00000000000000010000
9:  0,46364759050907880000  0,00000000000000010000
10: 0,46364761321561010000  0,00000000000000010000
11: 0,46364760803259750000  0,00000000000000010000
12: 0,46364760922469040000  0,00000000000000010000
13: 0,46364760894874296000  0,00000000000000010000
14: 0,46364760901297210000  0,00000000000000010000
15: 0,46364760899795077000  0,00000000000000010000
16: 0,46364760900147850000  0,00000000000000010000
17: 0,46364760900064694000  0,00000000000000010000
18: 0,46364760900084356000  0,00000000000000010000
19: 0,46364760900079693000  0,00000000000000010000
20: 0,46364760900080804000  0,00000000000000010000
21: 0,46364760900080537000  0,00000000000000010000
22: 0,46364760900080600000  0,00000000000000010000
23: 0,46364760900080580000  0,00000000000000010000
24: 0,46364760900080587000  0,00000000000000010000
25: 0,46364760900080587000  0,00000000000000010000
26: 0,46364760900080587000  0,00000000000000010000
27: 0,46364760900080587000  0,00000000000000010000
28: 0,46364760900080587000  0,00000000000000010000
29: 0,46364760900080587000  0,00000000000000010000
30: 0,46364760900080587000  0,00000000000000010000

第一列是我的计数器变量n
第二列是我计算出的arcTan - 你看到它在循环23后没有变得更精确 第3栏是我的Epsilon

如何检查第二列是否具有第3列中指定的精确度?

2 个答案:

答案 0 :(得分:1)

也许你需要改变

while(Math.abs(arcTan) < EPSILON || n < 70)

while(Math.abs(arcTan) < EPSILON && n < 70)

但在不知道循环内发生了什么的情况下不知道。

编辑:可能像

public final static double EPSILON = 1E-16; // Given Value 0,00000000000000010000
public static void main(String[] args)
{   
    double arcTan = formula;
    double previous = 0, current;

    while(n<70)
    {
        current = ...myAlgorythm...

        if (current - previous < EPSILON)
            break;
        else
            previous = current;
    }
}

答案 1 :(得分:0)

您需要计算Math.atan的结果与您自己的计算之间的差异(并将其与epsilon进行比较):

double arcTan = Math.atan(myValue);

while(Math.abs(arcTan - myArcTan) >= EPSILON && n < 70) {
    ...
}

编辑:将||替换为&&,与其他答案一样。