D
D
Domus2016-12-04 19:51:24
Java
Domus, 2016-12-04 19:51:24

Where is the error in the cosx series expansion algorithm?

Good afternoon!
I can’t write an algorithm for expanding cosx into a series for a day now - it gives out completely wrong. Please tell me what is the problem?

import java.util.Scanner;

class B17{
  public static void main(String[] args){
    final double E = 0.2;
    int n = 4;
    double[] x = {-0.2, 7.9, 19.2, 101,4};
    double[] answer = new double[n];
    double[] argCos = new double[x.length];
    for(int k=0; k<argCos.length; k++){
      argCos[k] = Math.pow(x[k],2)-x[k]+1;
    }
    
    double e, s, p, increaseX, g;
      double fact, factK, factKplus;
    
    for(int k=0; k<n; k++){
      s = 1; // Сумма шага
      increaseX = Math.pow(argCos[k], 2); // Коэф. пост увеличения x^(2i)
      g = 1; // Хранение x^(2i)
      e = 1; // Общая сумма 
      fact = 1; // Хранение факториала
      factK = 0; // Нынешнее уможение факториала
      factKplus = 1; // Максимальный множитель факториала
      p = 1; 
      while(Math.abs(s)>E){
        g = g*increaseX;
        factK = factKplus;
        factKplus = factKplus+2;
        for(; factK<factKplus; factK++){
          fact = fact*factK;
        }
        s = p*g/fact;
        e = e + s;
        p=-p;
      }
      answer[k] = e;
    }			
    
    for(int k=0; k<answer.length; k++){
      System.out.println("cos(" + argCos[k] + ") = " + answer[k]);
    }
  }
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
AVSomov, 2016-12-05
@AVSomov

Asking the right question is half the answer

To improve your understanding of the question:
1. First, indicate which series expansion is being used? Alternatively, the Taylor series: https://en.wikipedia.org/wiki/Trigonometric_functi... (but then the variable p must be initialized to "-1")
PS: If possible: make it procedural. At the moment, initialization of the test, calculation and output of the result are all in one method. (it's easy to get confused)

M
muzclubs, 2016-12-05
@muzclubs

Maybe BigInteger and bigdecimal should be used here? It's just that the numerator grows much faster than the denominator.

A
abcd0x00, 2016-12-06
@abcd0x00

You're making the wrong decision
https://toster.ru/answer?answer_id=927676
No need to store the factorial, it's not used in the solution at all, it's a trap for the stupid.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question