gpt4 book ai didi

java - 方法返回的除法 - 错误值

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:00:15 27 4
gpt4 key购买 nike

我有两种方法:幂和阶乘:

public static long pow(int x, int n) {
long p = x;
for (int i = 1; i < n; i++) {
p *= x;
}
return p;
}

public static long fact(int n) {
long s = n;
for (int i = 1; i < n; i++ ) {
s *= i;
}
return s;
}

返回多头。当我想在评估新方法时使用它们 Exponential function与 Math.exp(x) 相比,我得到了错误的结果。我的代码:

public static void exp(int x, double eps) {
int i = 1;
double pow = 1.0;
double fact = 1.0;
double sum = 0.0;
double temp;
do {
temp = pow/fact;
sum += temp;
pow = pow(x, i);
fact = fact(i);
i++;
}
while (temp > eps);
System.out.println("Check: " + Math.exp(x));
System.out.println("My: " + sum);
}

public static void main() {
int x = 10;
double eps = 0.0000000000001;

exp(x, eps);
}

x=10 的输出是:

Check: 22026.465794806718

My: 21798.734894914145

x 越大,“精度损失”越大(不完全是,因为你不能真正称之为精确......)。

不同之处在于,当方法 powerfactorial 返回 double 时,输出是正确的。任何人都可以向我解释如何让它发挥作用吗?

powfact 方法必须返回 long,我必须在 exp(大学作业)中使用它们。

最佳答案

如果您尝试这种 pow 方法:

public static long pow(int x, int n) {
long p = x;
System.out.println("Pow: "+x+","+n);
for (int i = 1; i < n; i++) {
p *= x;
System.out.println(p);
}
return p;
}

你得到这个输出:

...
Pow: 10,20
100
1000
10000
...
...
1000000000000000
10000000000000000
100000000000000000
1000000000000000000
-8446744073709551616
7766279631452241920

long 值溢出:10^20 太大而不适合 long。

Methods pow and fact must return long and I must use them in exp (college assignment).

然后你就没有太多办法来修复它了。如果 eps 太小,您可能会抛出异常。

关于java - 方法返回的除法 - 错误值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7967383/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com