Java程序给出了功能E^X的泰勒串联术语不正确


//java program that asks the user  to input a number that e^x=1+x+x^2/2! +x^3/3!... e is a mathematical constant equal to 2.718...
import java.util.Scanner;
public class taylor_2 {
  public static void main(String args[]) {
    Scanner input=new Scanner(System.in);
    double x; //input for x
    double factorial=1; //initializes factorial
    int counter=1; //initializes counter
    double result=1; //initializes result
    System.out.println("Enter non negative number"); //asks user to enter x
    x=input.nextInt();
 //output in while loop will continue to be generated if user doesn't entered a negative number
    while(x<1){
      System.out.println("I said entered a positive number");
      x=input.nextInt();
    }
    while(x>counter){
      factorial=factorial*counter;//factorial formula
      result=result+(Math.pow(x,counter))/factorial; //equation for e^x=1+x+x^2/2! +x^3/3!
      counter++;
    }
    System.out.println("Taylor series is " +result);//output for taylor equation e^x
  }
}

这是我的代码的输出:

输入非负数

2

泰勒系列是4.0

当我输入2时,它应该输出7.3890560983而不是4.0,因为e = 2.718 ...和e^2 = 7.3890560983。我在做什么错?

问题是泰勒系列与e^x不同。它将返回靠近函数e^x的函数。

为了更好地理解它,我建议您查看下一个链接的第二张图片:

https://en.wikipedia.org/wiki/taylor_series

您可以在上一张图片中看到,随着n的越来越大,功能变得越来越准确。

您的代码问题是您的x值是您的n值,这不是真的。

x:必须是您现在要的值e^x。

n:是您方程式的准确性。较大意味着更准确。

因此,您必须使用while(n>counter)更改while(x>counter),其中n可以是用户选择精度的变量,或者使用您选择的精度为常数。

我认为在x=100之前,n=150应该起作用。

我希望对您有帮助!:)

这里似乎有一个答案:即使算法与您的算法略有不同,to to to t to taylor series for c 。这是其Java版本:

public class TaylorSeries {
public static void main(String args[]) {
    Scanner input = new Scanner(System.in);
    System.out.println("Enter x:");
    double x = input.nextDouble();
    double result = calcExp(x);
    System.out.println("calcExp(x) = " + result);
    System.out.println("       e^x = " + Math.pow(Math.E, x));
}
static double calcExp(double x) {
    double eps = 0.0000000000000000001;
    double elem = 1.0;
    double sum = 0.0;
    boolean negative = false;
    int i = 1;
    sum = 0.0;
    if (x < 0) {
        negative = true;
        x = -x;
    }
    do {
        sum += elem;
        elem *= x / i;
        i++;
        if (sum > Double.MAX_VALUE) {
            System.out.println("Too Large");
            break;
        }
    }
    while (elem >= eps);
    return negative ? 1.0 / sum : sum;
}
}

输出:

Enter x:
2
calcExp(x) = 7.389056098930649
       e^x = 7.3890560989306495

所有信用都应在此处转到答案:Exp to Taylor系列。我只将C 代码转换为Java

最新更新