计算sin(x)w/oMath并仅在java中使用循环

asd*_*jkl 6 java loops trigonometry

我必须使用泰勒系列计算Math.sin(x):

ñ

对于n→∞,Σ(-1)^ i*(x ^(2i + 1)/(2i + 1)!)

I = 0

因此,我只允许使用循环(没有递归),我可能不会使用Math类.这是我走了多远:

public double sinLoops(double x) {
        int potenz1;
        double potenz2 = x;
        double fac = 1;
        double result = 0;

        do {
            if ((i % 2) == 0) {
                potenz1 = 1;
            } else {
                potenz1 = (-1);
            }

            for (int counter = 1; counter < (2 * i + 1); counter++) {
                potenz2 *= x;
            }
            for (int counter2 = (2 * i + 1); counter2 >= 1; counter2--) {
                fac *= counter2;
            }   
            result += potenz1 * potenz2 / fac;
            i++;
        } while (result > 0.0000001 || result < -0.0000001);
        return result;
    }
Run Code Online (Sandbox Code Playgroud)

但是,我认为我的中断条件不太正确(-1*10 ^ -7或1*10 ^ -7),返回的结果是NaN.我已经查过了,但我现在有点受到挑战,所以我希望有人可以帮助我.:)

提前致谢!

Tat*_*ize 5

  1. 你没有初始化我.
  2. 你检查了结果的最终条件而不是总和的taylor元素.
  3. 你离开了potenz2和fac元素以保持螺旋失控,而不是为系列中的每个新元素重置它们.
  4. 最终他们将达到无限和无限,划分并获得NaN.添加到运行结果的NaN是NaN,并且实际上为条件返回true并退出循环(NaN与条件有奇数效果).

这是工作代码,对问题进行评论.

    public double sinLoops(double x) {
        int i = 0; //this didn't exist.
        double result = 0;
        double seriesElement; //You need the individual taylor series element.
        do {
            double potenz2 = x; //these need to be reset each time.
            double fac = 1; //if not they overflow and infinity/infinity is NaN and it exits.
            int potenz1 = ((i & 1) == 1) ? -1 : 1; //this is just short hand.
            for (int counter = 1; counter < (2 * i + 1); counter++) {
                potenz2 *= x;
            }
            for (int counter2 = (2 * i + 1); counter2 >= 1; counter2--) {
                fac *= counter2; //we could actually keep the last iteration and do 2*(i-1)+1 to 2*i+1 each new i.
            }
            seriesElement = potenz1 * potenz2 / fac; //we need to save the value here.

            result += seriesElement; //we are summing them in the results.
            i++;

        } while (seriesElement > 0.0000001 || seriesElement < -0.0000001); //We check this conditional against the series element, *NOT THE RESULT*
        return result;
    }
Run Code Online (Sandbox Code Playgroud)

如果有人以某种方式需要这种方式来进行某种生产工作,速度是关键的(而且错误的答案是错误的,尽管在这种情况下使用数学),而不是"我可以为我做功课",这里是优化的代码:

public double sinLoops(double x) {
        double result = 0, powerx = -1, fac = 1;
        int i = 0, n, m = 0;
        while (true) {
            n = m;
            m = (i++*2) + 1;
            powerx *= -1;
            while (n < m) {
                powerx *= x;
                fac *= ++n;
            }
            if ((Double.isInfinite(fac)) || (Double.isInfinite(powerx))) break;
            result += powerx / fac;
        }
        return result;
    }
Run Code Online (Sandbox Code Playgroud)