A detailed example of java square root of sqrt algorithm
- 2020-06-15 09:11:03
- OfStack
Square root (sqrt) algorithm in java
The square root (sqrt, square root) is a common mathematical formula in mathematics;
There are two steps to find the square root by using the program:
Step 1: while() loop, control the number of loops and the number of decimal places, prevent infinite loop and the occurrence of multiple decimal places;
Step 2: By decomposing the square root, using a loop, gradually reduce to close to the square root;
Similarly, other square roots can be similarly extended, but it's important to note that,
You want to make sure that you put in a positive number;
The odd power square root should be converted to a positive number to ensure the cyclic convergence, and then the positive and negative judgment of the results should be made.
The code is as follows:
/*
* Algorithms.java
*
* Created on: 2013.12.03
* Author: Wendy
*/
/*eclipse std kepler, jdk 1.7*/
public class Algorithms
{
public static double sqrt(double c)
{
if(c<0) return Double.NaN; //NaN: not a number
double err = 1e-15; // minimum
double t = c;
while (Math.abs(t-c/t) > err*t) //t^2 Close to the c, To prevent the decimal
t = (c/t + t)/2.0;
return t;
}
public static double cbrt(double c)
{
boolean b = (c>0) ? true : false; // save c The symbol of
c = (c>0) ? c : -c;
double err = 1e-15;
double t = c;
while(Math.abs(t*t-c/t) > err*t)
t = (c/(t*t)+t)/2.0;
t = (b) ? t : -t;
return t;
}
public static void main(String[] args)
{
double r = sqrt(4.0);
System.out.println("sqrt(4.0) = " + r);
double rc = cbrt(-27.0);
System.out.println("cbrt(9.0) = " + rc);
}
}
Output:
sqrt(4.0) = 2.0
cbrt(9.0) = -3.0
Thank you for reading, I hope to help you, thank you for your support to this site!