Java 不使用数学库计算e^x

Java 不使用数学库计算e^x,java,Java,我知道在不使用数学库的情况下计算e^x的答案已经有了 但我有点怀疑: 我定义了两个单独的函数:一个是计算a^b的幂函数,另一个是计算n!的阶乘函数!。我声明这些函数是静态的,所以不需要创建对象 使用的逻辑: int l=1; // Declared a variable l and initialised it int sum=1; // The sum variable would be value of e^x for(l=1; ; l++) {

我知道在不使用数学库的情况下计算e^x的答案已经有了

但我有点怀疑:

我定义了两个单独的函数:一个是计算a^b的幂函数,另一个是计算n!的阶乘函数!。我声明这些函数是静态的,所以不需要创建对象

使用的逻辑:

    int l=1; // Declared a variable l and initialised it

    int sum=1;    // The sum variable would be value of e^x

   for(l=1; ; l++)

   {
     sum= sum+ (power(x,l))/(factorial(l)) ; /* Here x is taken as user input and functions are 
                                                 called*/
    }

    System.out.println("The value of e^ "+x +" is " +sum);

  For infinite loop as shown in above code it says unreachable code.
  If i put a condition on l like l<34 then code runs but for l<35 it prints that the value of e^x is infinity.

      So how to get rid of this problem???

我看到这里出现了很多问题。首先,计算e的精确值是不可能的,因为它是一个无限循环。第二,你所有的变量,可能甚至是阶乘和幂函数中的变量都被声明为int,当然e不是int,计算也不会返回int。第三,我不明白幂函数的意图。第四,试着把你的问题分成几个小问题,用不同的功能来解决它们。关于计算欧拉常数,这里有一种方法:

public static double calculateE(int noOfCalculations){

    double e = 0;
    for(int i=0;i<noOfCalculations;i++) 
        e += (double)1/factorial(i); 
    return e;   

}

public static int factorial(int i) {
    if(i==0)
        return 1;
    return i*factorial(i-1);
}

你能同时显示幂和阶乘吗?那很好。但是如何摆脱无限循环的问题呢??如果有人问我这个问题的代码,我能不能把上面的代码和你提到的修改一起呈现出来?为了避免无限循环,你必须确定你想要的准确度。这也是一道数学题。例如你可以说;e=2.71或e=2.71828182845904523。为了确定准确度,我们放置了一个名为noOfCalculations的方法变量,以确定我们想要的准确度。至于演示,这取决于你为谁和什么演示,但我可以向你保证,世界上没有计算机科学家或数学家说解决方案是错误的,也不是好方法。