在Java中不使用内置函数计算e^x
我是一名Java初学者,目前正在阅读《如何像计算机科学家一样思考》入门书。我在迭代一章中遇到了一个问题。谁能给我指一下正确的方向吗
当我使用数学时。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
}
}
# 1 楼答案
这里有几个错误:
总而言之,您可以将操作简化为:
编辑:
-我运行了代码,看到了数学。exp(power)是打印出来的,而不是数学。exp(x)
-我的第一项是错误的,因为sum被初始化为myX
# 2 楼答案
赋值
denom = denom*(denom+1)
将给出如下序列:1, 1*2=2, 2*3=6, 6*7=42, 42*43=...
但是你想要denom = denom*count
一般来说,我们只想打印第一个
n
阶乘,从1!
:1!, 2!, 3!, ..., n!
开始。在第k
项,我们取第k-1
项并乘以k
。这将是在前一项上递归计算k!
。具体例子:4!
是3!
次4
,6!
是5!
次6
在代码中,我们有
试着运行上面的程序,比较一下运行下面的程序会得到什么结果:
# 3 楼答案
为什么要把它复杂化?我尝试了一个解决方案,结果如下:
如果你想像工程师一样思考,我会这样做:
希望你喜欢
# 4 楼答案
我尝试了一个解决方案,结果如下: