Problem:
Design an algorithm to evaluate the cos(x) as defined by the infinite series expansion
Cos(x) = 1 - x2/2! + x4/4! - x6/6! + ..........
Solution:
package com.myprograms;
import java.util.Scanner;
public class CosFunction {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("enter radious value");
double x = s.nextDouble();
double sum = 1.0;
for(int i=2,j=1; i<20; i = i+2,j++){
sum += Math.pow(-1, j) * Math.pow(x, i) / findFactorial(i);
}
System.out.println(sum);
s.close();
}
public static int findFactorial(int n){
int product = 1;
for(int i=1; i<= n; i++){
product = product * i;
}
return product;
}
}
Output:
enter radious value
1.047
0.5001710767161183
Design an algorithm to evaluate the cos(x) as defined by the infinite series expansion
Cos(x) = 1 - x2/2! + x4/4! - x6/6! + ..........
Solution:
package com.myprograms;
import java.util.Scanner;
public class CosFunction {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("enter radious value");
double x = s.nextDouble();
double sum = 1.0;
for(int i=2,j=1; i<20; i = i+2,j++){
sum += Math.pow(-1, j) * Math.pow(x, i) / findFactorial(i);
}
System.out.println(sum);
s.close();
}
public static int findFactorial(int n){
int product = 1;
for(int i=1; i<= n; i++){
product = product * i;
}
return product;
}
}
Output:
enter radious value
1.047
0.5001710767161183
No comments:
Post a Comment