Skip to content

Core\Math::sqrt

Core\Math::sqrt returns the square root of a number. The square root of 9.0 is 3.0, because 3.0 * 3.0 is 9.0.

The result is a float. A negative number has no square root, so the result is NaN (a value that means "not a number"). Core\Math::sqrt does not throw an error for it. Use Core\Math::isNan to check the result. -0.0 gives -0.0, and Core\Math::INFINITY gives Core\Math::INFINITY.

The examples below show the square roots of simple numbers, then negative numbers and special values, then how much a list of response times varies.

Parameters

  • $nfloatThe number to take the square root of.

Return value

Returns float. A float that is zero or more. A negative $n gives NaN. -0.0 gives -0.0, and Core\Math::INFINITY gives Core\Math::INFINITY.

Examples

Square roots

<?nvs
// Shows the square roots of a few simple numbers.
// These numbers are squares of other numbers. This prints 3, 0.5 and 12.
echo Core\Math::sqrt(9.0), "\n";
echo Core\Math::sqrt(0.25), "\n";
echo Core\Math::sqrt(144.0), "\n";
// The square root of 2 has no end. This prints 1.4142135623731.
echo Core\Math::sqrt(2.0), "\n";
Output
3
0.5
12
1.4142135623731

Negative and special values

<?nvs
// Shows the result for a negative number, negative zero and infinity.
// A negative number has no square root. The result is `NaN`, and this prints NAN.
float $root = Core\Math::sqrt(-4.0);
echo $root, "\n";
// `Core\Math::isNan` checks the result. This prints "No square root".
if (Core\Math::isNan($root)) {
echo "No square root\n";
}
// Negative zero stays negative zero, and infinity stays infinity. This prints -0, then INF.
echo Core\Math::sqrt(-0.0), "\n";
echo Core\Math::sqrt(Core\Math::INFINITY), "\n";
Output
NAN
No square root
-0
INF

Spread of response times

<?nvs
// Shows how a monitoring page finds how much response times vary (the standard deviation).
class Stats
{
// Returns the standard deviation: the square root of the average squared distance
// from the average.
public static function spread(array<float> $times): float
{
float $sum = 0.0;
float $count = 0.0;
foreach ($times as float $time) {
$sum = $sum + $time;
$count = $count + 1.0;
}
float $average = $sum / $count;
float $squares = 0.0;
foreach ($times as float $time) {
float $distance = $time - $average;
$squares = $squares + $distance * $distance;
}
return Core\Math::sqrt($squares / $count);
}
}
// The average is 100 ms. This prints a spread of 28.3 ms.
array<float> $times = [120.0, 80.0, 100.0, 140.0, 60.0];
echo 'Spread: ', Core\Math::round(Stats::spread($times), { precision: 1 }), " ms\n";
Output
Spread: 28.3 ms