Jump to content

Welcome to Geeks to Go - Register now for FREE

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

  • Please log in to reply



    New Member

  • Member
  • Pip
  • 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;

	  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;
	   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





  • Member
  • PipPipPip
  • 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:

Microsoft Yahoo BBC MSN PC Magazine Washington Post HP