Recursively calculate e^x with Java using MacLaurin Series

强颜欢笑 提交于 2021-02-11 10:02:55

问题


I need to write a recursive java method that will compute e^x called e(x,n) with the signature,

public static double eThree(double x, long n) 

and it must use the MacLaurin series to compute e^x, which is the following observation:

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

With some help earlier, I was able to make one that didn't require this format, but I'm not sure what I would code in order to use the format above. Thanks guys, really appreciate any help that will be given!


回答1:


Does this work for you? I believe it implements the algorithm but it does not produce 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;
}

it seems to think that:

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



回答2:


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);
  }
}

Can't test it now though.




回答3:


If I understand correctly, n here should represent the precision of the McLaurin series (i.e. up to how many terms we calculate). In that case, you should decrement the n counter every time you invoke the method recursively. You could write something like:

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);
  }
}


来源:https://stackoverflow.com/questions/22065279/recursively-calculate-ex-with-java-using-maclaurin-series

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!