Skip to content

Core\Math::toRadians

Converts an angle from degrees to radians. Core\Math::sin, Core\Math::cos and Core\Math::tan need the angle in radians, so you use this first when your angle is in degrees. A full circle is 360 degrees or 2 * PI radians, so 180 degrees is PI radians. Core\Math::toDegrees converts the other way. An infinity gives an infinity, and NaN (a value that means "not a number") gives NaN.

The examples below show a few angles, then a conversion to radians and back, then how a map app finds the distance between two cities.

Parameters

  • $degreesfloatThe angle, in degrees.

Return value

Returns float. The same angle in radians. Core\Math::toRadians(180.0) is PI. An infinity gives an infinity, and NaN gives NaN.

Examples

A few angles

<?nvs
// Shows a few angles in degrees converted to radians.
// Half a circle is `PI` radians. This prints 3.1415926535898.
echo Core\Math::toRadians(180.0), "\n";
// A full circle is `2 * PI` radians. This prints 6.2831853071796.
echo Core\Math::toRadians(360.0), "\n";
// A negative angle gives a negative result. This prints -0.78539816339745.
echo Core\Math::toRadians(-45.0), "\n";
Output
3.1415926535898
6.2831853071796
-0.78539816339745

There and back

<?nvs
// Shows an angle converted to radians and back to degrees.
float $radians = Core\Math::toRadians(30.0);
// This prints 0.5235987755983.
echo $radians, "\n";
// `Core\Math::toDegrees` converts it back. The result is exactly 30, so this prints yes.
echo Core\Math::toDegrees($radians) == 30.0 ? 'yes' : 'no', "\n";
Output
0.5235987755983
yes

Distance between cities

<?nvs
// Shows how a map app finds the distance between two cities from their positions in degrees.
class Distance
{
// This is the haversine formula. It finds the shortest distance over the surface of the Earth.
public static function km(float $lat1, float $lon1, float $lat2, float $lon2): float
{
float $a1 = Core\Math::toRadians($lat1);
float $a2 = Core\Math::toRadians($lat2);
float $halfLat = Core\Math::toRadians($lat2 - $lat1) / 2.0;
float $halfLon = Core\Math::toRadians($lon2 - $lon1) / 2.0;
float $h = Core\Math::sin($halfLat) ** 2.0
+ Core\Math::cos($a1) * Core\Math::cos($a2) * Core\Math::sin($halfLon) ** 2.0;
// 6371 is the radius of the Earth in kilometers.
return Core\Math::round(2.0 * 6371.0 * Core\Math::asin(Core\Math::sqrt($h)));
}
}
// From Berlin to Paris. This prints 877.
echo Distance::km(52.52, 13.405, 48.8566, 2.3522), "\n";
// From New York to London. This prints 5570.
echo Distance::km(40.7128, -74.006, 51.5074, -0.1278), "\n";
Output
877
5570