0 Replies - 269 Views - Last Post: 06 November 2009 - 08:34 PM

#1 erik.price   User is offline

  • D.I.C Lover
  • member icon

Reputation: 486
  • View blog
  • Posts: 2,690
  • Joined: 18-December 08

Finding the nth Root of a Number

Posted 06 November 2009 - 08:34 PM

Description: So this is the third method I've submitted today dealing with finding roots, and by now you probably think I have an obsession. (I don't, Wikipedia's related article links practically clicked themselves)Finds the nth root of a number with a simple algorithm
public static double nRoot(int n, double num, double epsilon)
		{
                        //if you weren't sure, epsilon is the precision
			int ctr = 0;
			double root = 1;
			if(n <= 0)
				return Double.longBitsToDouble(0x7ff8000000000000L);
			//0x7ff8000000000000L is the Java constant for NaN (Not-a-Number)
			if(num == 0) //this step is just to reduce the needed iterations
				return 0;
			while((Math.abs(Math.pow(root, n) - num) > epsilon) && (ctr++ < 1000)) //checks if the number is good enough
			{
				root = ((1.0/n)*(((n-1.0)*root)+(num/Math.pow(root, n-1.0))));
			
			}
			return root;
		}

//just a reminder: this method doesn't allow for n being anything besides a positive (non 0) int


Is This A Good Question/Topic? 0
  • +

Page 1 of 1