 Geeks To Go is a helpful hub, where thousands of volunteer geeks quickly serve friendly answers and support. Check out the forums and get free advice from the experts. Register now to gain access to all of our features, it's FREE and only takes one minute. Once registered and logged in, you will be able to create topics, post replies to existing threads, give reputation to your fellow members, get your own private messenger, post status updates, manage your profile and so much more.

Create Account How it Works # Taylor Series

### #1  DeepIndian Posted 14 March 2010 - 05:12 PM

DeepIndian

New Member

• • Member
• • 2 posts
I need to remove math.pow and factorial and put something that will still calculate and get me same results.

```package myexp;

import java.util.Scanner;

public class Main {

public static void main(String args[]) {
double x, n, sum = 1;
int i;

System.out.println("Enter the value of x: ");

System.out.println("Enter the value of n: ");
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;
}
}```

• 0

### #2  W-Unit Posted 25 May 2010 - 06:02 PM

W-Unit

Member

• • Member
•   • 170 posts
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.
```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;
}```

• 0

### Similar Topics

#### 0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users

### As Featured On:       