alternating series sum java help
For my assignment I have to create a program that calculates the following:
x - x^3/3! + x^5/5! - x^7/7! + ..... + - x^n/n!
Where the user inputs the value of x they want to calculate and inputs the value of n for the maximum exponent value (the higher the exponent the user inputs the more accurate the calculation will be).
Here's my attempt to the problem:
Code:
import java.io.*;
public class s {
public static void main(String args[]) throws IOException
{
BufferedReader keybd = new BufferedReader(new InputStreamReader(System.in));
double x;
int n;
System.out.print("Input a value for x: ");
x = Double.parseDouble(keybd.readLine());
System.out.print("Input max exponent: ");
n = Integer.parseInt(keybd.readLine());
int factorial=1;
for (int i=2; i<=n; i++) // this for loop finds factorials (ie 5!=120)
{
factorial = factorial * i;
}
int exp=1;
double sum = 0;
for (int i=1; i<=n; i=i+2)
{
sum = sum + (Math.pow(-1,i))*(Math.pow(x,i))/(factorial);
// i don't think I did the factorial part correctly.
// Also I can't get the alternating between positive and negative. it starts with negative because (-1)^1= -1 but the first term of series has to be positive.
}
System.out.println("The result is: " + sum);
}
}
Please help! Thanks!