Jump to content

Welcome to Geeks to Go - Register now for FREE

Need help with your computer or device? Want to learn new tech skills? You're in the right place!
Geeks to Go is a friendly community of tech experts who can solve any problem you have. Just create a free account and post your question. Our volunteers will reply quickly and guide you through the steps. Don't let tech troubles stop you. Join Geeks to Go now and get the support you need!

How it Works Create Account
Photo

Taylor Series


  • Please log in to reply

#1
DeepIndian

DeepIndian

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

Advertisements


#2
W-Unit

W-Unit

    Member

  • 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