Answer the question
In order to leave comments, you need to log in
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
Asking the right question is half the answer
Maybe BigInteger and bigdecimal should be used here? It's just that the numerator grows much faster than the denominator.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question