write a programme to calculate the square root of a number

Dani AI

Generated

asked for a program to compute a square root. As and noted, most languages expose a built-in sqrt. For Python the simplest, fastest and clearest options depend on whether you want a floating result, an integer floor result, or support for negative inputs.

Use the standard library for common cases:

import math
n = 16.0
print(math.sqrt(n))    # float result

A short alternative is the exponent operator:

n = 16.0
print(n ** 0.5)

Handle negatives or complex results with cmath:

import cmath
print(cmath.sqrt(-4))  # 2j

If an exact integer floor root is needed (Python 3.8+):

import math
print(math.isqrt(17))  # 4

If a manual algorithm is wanted for learning, control or custom precision, Newton-Raphson is simple and fast:

def sqrt_newton(n, tol=1e-12):
    if n < 0:
        raise ValueError("negative input")
    if n == 0:
        return 0.0
    x = float(n)
    while True:
        nx = 0.5 * (x + n / x)
        if abs(x - nx) < tol:
            return nx
        x = nx

Notes and further reading: prefer the built-ins for correctness and performance. Floating-point results have limited precision; use the decimal module for high-precision needs. For documentation see the Python docs for math.sqrt, cmath.sqrt, math.isqrt, and background on Newton's method at Newton's method.

Recommended Answers

All 3 Replies

double mySquareRoot = Math.Sqrt(number)

ex :

Interaction.MsgBox(Math.Sqrt(9));

if this thread was solved then please mark it as Solved. so other member can find it easily if they had a same problem. :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.