我在计算无限级数中的π值时有点卡住了:
π=4-4/3+4/5-4/7+4/9-4/11+.
问题必须解决的是“打印一个表,该表显示π的值,该表通过计算本系列的前200,000项来近似。在获得以3.14159开头的值之前,您必须使用多少个术语?”
我不确定我用来找这个词的条件是否正确。有人能告诉我这是对还是错,如果不是,有什么正确的方法来做到这一点?我怀疑它与Java数字的运行方式有关。
package com.company;
public class Main {
public static void main(String[] args) {
double result = 0;
int j = 1;
int k = 1; //controls the if part for finding the term
int term = 0; //variable for term that we're looking for
for (int i = 1; i <= 200000; i += 1) {
if ((i % 2) != 0) {
result += (double) 4 / j; //positive part
j += 2;
}
else {
result -= (double) 4 / j; //negative part
j += 2;
}
if (k != 0) {
/* Attempts to detect when result == 3.14159 */
if (result > 3.14158 && result < 3.14160) {
term = i;
k = 0;
}
}
System.out.printf("%f\n", result);
}
System.out.println("Term at which pi has value 3.14159: " + term);
}
}
发布于 2020-03-02 15:48:23
要检查以3.14159开头的数字,您需要检查大于或等于该值的值,并且小于3.14160:
if (result >= 3.14159 && result < 3.14160) {
..
}
通过这一更改,我得到了term
值为136121,我已经在其他地方验证了这一点,这是预期的答案。
不需要对结果进行任何乘法和舍入操作,因为所需的精度范围(6位小数)远小于double
提供的精度范围。
发布于 2020-03-02 15:37:43
Java Math
类是您的朋友。文档在这里:https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html
我倾向于使用Math.floor(result * 100000) == 314159)
进行测试。
您还可能希望在结果中包括i
,这样您就可以轻松地根据表检查您的答案。
最后,我将使用boolean
而不是int
来进行测试。
发布于 2020-03-02 16:34:16
我将@Alnitak的建议合并到代码中,为您提供了一些其他的想法,比如如何优化它,以及如何使用该语言。我稍微调整了一下,再迭代一个数量级,再产生一个小数点的精度。但是,大多数语言使用的IEEE754浮点数学所遇到的限制是,浮点数是如何在内部表示的。许多数字实际上不是一个数字,例如无法表示。所以有四舍五入。我肯定美国宇航局有办法解决这个问题:-)我不是数学家,但可能有论文讨论在你的问题范围之外,实现更高精度的技术。
public class Main {
private final static int MAX_LOOP = 2000000;
private static int i = 1;
public static void main(String[] args) {
double j = 1.0, result = 0.0;
for ( ; i < MAX_LOOP; i++, j += 2.0) {
if ((i % 2) != 0)
result += 4.0 / j;
else
result -= 4.0 / j;
if (result >= 3.141592 && result < 3.141593)
break;
System.out.println(result);
}
if (i < MAX_LOOP)
System.out.println("Term at which pi has value 3.141592..." + result + " = " + i);
else
System.out.println("Couldn't find pi using series with maximum iterations = " + MAX_LOOP);
}
}
https://stackoverflow.com/questions/60491991
复制相似问题