我是 Java 初学者,目前正在阅读《如何像计算机科学家一样思考》初学者书籍。我在迭代章节中遇到了一个问题。谁能指出我正确的方向吗?
当我使用 math.exp 时,我得到的答案与我的代码获得的答案完全不同。 请注意,这不是作业。
问题是:
One way to calculate ex is to use the infinite series expansion ex = 1 + x + x2 /2! + x3/3! + x4/4! +
...
If the loop variable is namedi
, then the ith term is xi
/i
!.
- Write a method called
myexp
that adds up the firstn
terms of this series.
所以这是代码:
public class InfiniteExpansion {
public static void main(String[] args){
Scanner infinite = new Scanner(System.in);
System.out.println("what is the value of X?");
double x = infinite.nextDouble();
System.out.println("what is the power?");
int power = infinite.nextInt();
System.out.println(Math.exp(power));//for comparison
System.out.println("the final value of series is: "+myExp(x, power));
}
public static double myExp(double myX, double myPower){
double firstResult = myX;
double denom = 1;
double sum =myX;
for(int count =1;count<myPower;count++){
firstResult = firstResult*myX;//handles the numerator
denom = denom*(denom+1);//handles the denominator
firstResult = firstResult/denom;//handles the segment
sum =sum+firstResult;// adds up the different segments
}
return (sum+1);//gets the final result
}
}
最佳答案
赋值 denom = denom*(denom+1)
将给出如下序列:1, 1*2=2, 2*3=6, 6*7 =42, 42*43=...
但你想要denom = denom*count
。
一般来说,我们只想打印以 1!
开头的前 n
个阶乘:1!, 2!, 3!, ... ,n!
。在第 k 项,我们取第 k-1 项并乘以 k。这将是对前一项递归计算k!
。具体示例:4!
是 3!
乘以 4
,6!
是 5!
乘以 6
。
在代码中,我们有
var n = 7;
var a = 1;
for (int i = 1; i <= n; i++ ) {
a = a*i; // Here's the recursion mentioned above.
System.out.println(i+'! is '+a);
}
尝试运行上面的代码并进行比较,看看运行以下代码会得到什么:
var n = 7;
var a = 1;
for (int i = 1; i <= n; i++ ) {
a = a*(a+1);
System.out.println('Is '+i+'! equal to '+a+'?');
}
关于java - Java 中无需内置函数即可计算 e^x,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26140238/