package myexp; import java.util.Scanner; public class Main { public static void main(String args[]) { double x, n, sum = 1; int i; Scanner read = new Scanner(System.in); System.out.println("Enter the value of x: "); x = read.nextDouble(); System.out.println("Enter the value of n: "); n = read.nextDouble(); System.out.println (); for(i = 1; i <= n; i++) { sum += myexp(x,i); } System.out.println (sum); } public static double myexp( double x, int i) { if (i == 1) return x; else return Math.pow (x, i)/ factorial (i); } public static double factorial(double x, int n) { double factorial = 1.0; int i = 1; while (i <= n) { factorial = factorial * i; i = i + 1; } return factorial; } }
Taylor Series
Started by
DeepIndian
, Mar 14 2010 05:12 PM
#1
Posted 14 March 2010 - 05:12 PM
#2
Posted 25 May 2010 - 06:02 PM
Why does your factorial function accept two parameters? Factorials are a unary (one-parameter) operation. That is, you take "5 factorial" or "10 factorial" - not "5 factorial 2." The latter phrase makes no sense.
Anyways, the following code should work for all factorials, and all integer exponents greater than zero. You may want to edit the code for myexp so that it throws an exception if you try to evaluate a negative exponent; currently it will just loop infinitely in this case.
Anyways, the following code should work for all factorials, and all integer exponents greater than zero. You may want to edit the code for myexp so that it throws an exception if you try to evaluate a negative exponent; currently it will just loop infinitely in this case.
public static double factorial(int x) { if (x == 0) return 1; else if (x < 0) { return -1; } // Throw some exception- cannot take factorial of a negative number else return x * factorial(x - 1); } public static double myexp(double x, int n) { double result = x; for (; n > 1; n--) { result *= x; } return result; }
Similar Topics
0 user(s) are reading this topic
0 members, 0 guests, 0 anonymous users