Java在简单方程中重复十进制 [英] Java repeating decimal in simple equation
问题描述
我正在完成一项学校作业,其中我解决了一个涉及圆圈坐标的方程式(r ^ 2 = x ^ 2 + y ^ 2)r = 1,并且你通过x值递增求解y。我得到一个重复的小数,即使我只增加了十分之一。我不知道为什么,并以几种不同的方式尝试过它。这是代码。
I am doing a school assignment in which I solve an equation involving coordinates in a circle (r^2 = x^2 + y^2) were r = 1, and you increment through x values solving for y. I am getting a repeating decimals even though I only incrementing in tenths. I have no idea why and have tried it in a few different ways. Here is the code.
double r = 1;
double rSqr;
double x = 1;
double xSqr;
double y;
double ySqr;
double inc = 0.1;
int count = 0;
while(x > -r)
{
x = r - (count * inc);
rSqr = Math.pow(r, 2);
xSqr = Math.pow(x, 2);
ySqr = rSqr - xSqr;
y = Math.sqrt(ySqr);
count++;
System.out.println(x + " " + y);
}
输出为
1.0 0.0
0.9 0.4358898943540673
0.8 0.5999999999999999
0.7 0.714142842854285
0.6 0.8
0.5 0.8660254037844386
0.3999999999999999 0.9165151389911681
0.29999999999999993 0.9539392014169457
0.19999999999999996 0.9797958971132712
0.09999999999999998 0.99498743710662
0.0 1.0
-0.10000000000000009 0.99498743710662
-0.20000000000000018 0.9797958971132712
-0.30000000000000004 0.9539392014169457
-0.40000000000000013 0.9165151389911679
-0.5 0.8660254037844386
-0.6000000000000001 0.7999999999999999
-0.7000000000000002 0.7141428428542849
-0.8 0.5999999999999999
-0.9000000000000001 0.43588989435406705
-1.0 0.0
推荐答案
问题是 double
不精确。它使用64位来表示十进制数;一些位用于数字部分,一些用于指数,但许多看似简单的十进制数不能以这种方式准确表示,例如 0.1
。有关详情,请参见此Wiki文章。
The problem is that double
is imprecise. It uses 64 bits to represent decimal numbers; some bits are used for the numeric part, and some for the exponent, but many seemingly simple decimal numbers can not be accurately represented in this way, for example 0.1
. See this wiki article for more.
解决问题的一种方法是使用 DecimalFormat
显示数字,这可以将数字四舍五入以用于演示目的。下面是一些示例代码:
One way around the problem is to display the number using DecimalFormat
, which can round the number for presentation purposes. Here's some example code:
public static void main(String[] args) {
DecimalFormat decimalFormat = new DecimalFormat("#0.000");
double d = 1 - .9; // one way to get a repeating decimal floating point number
System.out.println(d);
System.out.println(decimalFormat.format(d));
}
输出:
0.09999999999999998
0.100
这篇关于Java在简单方程中重复十进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!