Square Root - Newton's method
Definition​
- Definition
- Explanation
- Guidance
- Tips
Newton's method is an iterative algorithm used for finding successively better approximations to the roots of a real-valued function. In the context of finding the square root of a number, Newton's method can be applied iteratively to converge upon the square root
Involves repeatedly refining an initial guess until it is close enough to the actual square root. It achieves this by using the tangent line of the function at each guess to find a better approximation. This process continues until the approximation is within an acceptable range of the actual square root
- Choose an initial guess for the square root, preferably close to the actual square root
- Calculate the next approximation:
next_guess = (current_guess + (number / current_guess)) / 2
- Check if the difference between the current guess and the next guess is within a predefined tolerance
- If the tolerance is met, the current guess is the square root. If not, repeat steps 2 and 3 with the next guess as the current guess
- Continue iterating until the tolerance is satisfied, producing successively better approximations of the square root
- choose the initial guess wisely to expedite convergence
- adjust the tolerance level based on the desired accuracy versus computational cost trade-off
- ensure proper handling of edge cases such as zero or negative input numbers
Practice​
- Practice
- Solution
square_root(number, tolerance):
// Initialize the initial guess
guess = number / 2
// Iterate until convergence
while true:
// Calculate the next guess
next_guess = (guess + (number / guess)) / 2
// Check if the tolerance is met
if abs(next_guess - guess) < tolerance:
return next_guess
// Update the current guess
guess = next_guess
package main
import (
"math"
)
func SqrtNewton(x float64) float64 {
z := x / 2
for i := 0; i < 10; i++ {
z -= (z*z - x) / (2 * z)
}
return z
}
public class Main {
public static double sqrtNewton(double x) {
double z = x / 2;
for (int i = 0; i < 10; i++) {
z -= (z * z - x) / (2 * z);
}
return z;
}
}
function sqrtNewton(x) {
let z = x / 2;
for (let i = 0; i < 10; i++) {
z -= (z * z - x) / (2 * z);
}
return z;
}
fun sqrtNewton(x: Double): Double {
var z = x / 2
repeat(10) {
z -= (z * z - x) / (2 * z)
}
return z
}
def sqrt_newton(x):
z = x / 2
for _ in range(10):
z -= (z*z - x) / (2 * z)
return z
fn sqrt_newton(x: f64) -> f64 {
let mut z = x / 2.0;
for _ in 0..10 {
z -= (z * z - x) / (2.0 * z);
}
z
}
function sqrtNewton(x: number): number {
let z: number = x / 2;
for (let i: number = 0; i < 10; i++) {
z -= (z * z - x) / (2 * z);
}
return z;
}