使用MacLaurin Series以Java递归计算e ^ x

时间:2014-02-27 10:12:32

标签: java recursion

我需要编写一个递归的java方法来计算带有签名的e ^ x e(x,n),

public static double eThree(double x, long n) 

并且它必须使用MacLaurin系列来计算e ^ x,这是以下观察:

1 + x(1 + x/2( 1 + x/3(1 + x/4(1 + ... ))))
e(x,0)= 1 A call to this would return a result of 1

之前有一些帮助,我能够制作一个不需要这种格式的,但我不确定为了使用上面的格式我会编码什么。谢谢你们,非常感谢你们给予的任何帮助!

3 个答案:

答案 0 :(得分:0)

这对你有用吗?我相信它实现了算法,但它不会产生x ^ n。

public static double eThree(double x, long n) {
    return eThree(x, n, 1);
}

private static double eThree(double x, long n, int div) {
    double d = 1;
    if (n > 0) {
        d = d + (x / div) * (eThree(x, n - 1, div + 1));
    }
    return d;
}
似乎认为:

2^0 = 1.0
2^1 = 3.0
2^2 = 5.0
2^3 = 6.333333333333333
2^4 = 7.0
2^5 = 7.266666666666667
2^6 = 7.355555555555555
2^7 = 7.3809523809523805
2^8 = 7.387301587301588
2^9 = 7.388712522045855

答案 1 :(得分:0)

public static double eThree(double x, long n) {
  return eThreeRec(x, n, 1);
}

public static double eThreeRec(double x, long n, long i){
  if(i==1) return 1;
  else{
    return 1 + (x/i)*eThreeRec(x, n, i+1);
  }
}

现在无法测试。

答案 2 :(得分:0)

如果我理解正确,n这里应该代表McLaurin系列的精确度(即我们计算的项数)。在这种情况下,每次以递归方式调用方法时,都应减少n计数器。你可以这样写:

public static double eThree(double x, long n) {
  return eThreeRec(x, n, 1);
}

public static double eThreeRec(double x, long n, long i) {
  if( i >= n ) {
    return 1.0;
  } else {
    return 1.0 + (x/i) * eThreeRec(x, n, i + 1);
  }
}