-3

我试图不导入要使用的数学类,但我仍在尝试估计常数“e”。据说 e= 1+(1/1!)+(1/2!)+(1/3!)+(1/4!)+(1/5!)+.....

这些是我在顶部的 int

String userInput;
int uIp; // this converts the string into int type 
double e = 2;

然后我问一些问题然后我检查看看不是零退出并且非负继续

While(uIp >0){
  final int endTheLoop = 15;
  int factorialNumber = 1;
  double e2TheUserInput=0;

  for(int i = 2; i < endTheLoop; i++){
    for(int j = 1; j < i; j++){  
      factorialNumber = ((i - 1) * factorialNumber);
    }
    e = (1/factorialNumber) + e;
    e2TheUserInput = Math.pow(e,uIp);
  }
}
4

2 回答 2

1

你正在做整数除法(但 e 是双倍的吗?):

e = (1/factorialNumber) + e;

更正为:

e = (1.0/(double)factorialNumber) + e;

它正在计算所有循环,但根据整数除法变化为零。:)

e= 2+(0)+(0)+(0)+(0)+.....

于 2012-09-10T15:19:42.163 回答
0

我不确定你的代码试图做什么,但如果你想计算 exp(x) 这就是我会做的。

public static void main(String... args) {
    for (int i = -4; i <= 4; i++)
        System.out.println(i + ": " + exp(i) + " cf " + Math.exp(i));
}

private static double exp(double d) {
    if (d < 0)
        return 1 / exp(-d);
    double e = 1, term = 1;
    for (int i = 1; i < 20 || term > e * 1e-16; i++) {
        term *= d / i;
        e += term;
    }
    return e;
}

对于大指数,在不使用泰勒级数的情况下评估积分幂会更有效。

public static final double E = 2.7182818284590452354;

private static double exp(double d) {
    if (d < 0)
        return 1 / exp(-d);
    long num = (long) d;
    double numE = 1;
    double mult = E;
    while (num > 0) {
        if ((num & 1) != 0)
            numE *= mult;
        num >>>= 1;
        mult *= mult;
    }
    double fract = d - (long) d;
    double fractE = 1, term = 1;
    for (int i = 1; i < 20; i++) {
        term *= fract / i;
        fractE += term;
    }
    return numE * fractE;
}
于 2012-09-10T15:43:35.893 回答