Core\Math::cos
Returns the cosine of an angle. The angle is in radians, and Core\Math::toRadians converts degrees to radians. The result is always from -1.0 to 1.0. An infinity or NaN (a value that means "not a number") gives NaN.
In plain words: draw a line of length 1 from the centre of a circle, at the angle you give. The cosine is how far the end of that line is to the right of the centre.
Good to know: the result is not always exact. The cosine of 90 degrees is zero, but the result is a tiny number close to zero. Round the result when you show it.
The examples below show the cosines of a few angles, then angles in degrees and rounding, then how far a sloped path goes on a map.
Parameters
$radiansfloatThe angle, in radians.Core\Math::toRadiansconverts degrees to radians.
Return value
Returns float. A number from -1.0 to 1.0. An infinity or NaN gives NaN.
Examples
Cosines of angles
<?nvs// Shows the cosines of a few angles in radians.
// The cosine of 0 is 1. This prints 1.echo Core\Math::cos(0.0), "\n";
// `Core\Math::PI` radians is half a circle. This prints -1.echo Core\Math::cos(Core\Math::PI), "\n";
// A negative angle has the same cosine as the positive one. Both lines print 0.54030230586814.echo Core\Math::cos(1.0), "\n";echo Core\Math::cos(-1.0), "\n";1-10.540302305868140.54030230586814Degrees and rounding
<?nvs// Shows how to use an angle in degrees, and why you round the result.
// `Core\Math::toRadians` converts 60 degrees to radians. This prints 0.5.echo Core\Math::cos(Core\Math::toRadians(60.0)), "\n";
// The cosine of 90 degrees is zero, but the result is a tiny number.// This prints 6.1232339957368E-17.echo Core\Math::cos(Core\Math::toRadians(90.0)), "\n";
// Rounding to 10 digits after the point gives zero. This prints 0.echo Core\Math::round(Core\Math::cos(Core\Math::toRadians(90.0)), { precision: 10 }), "\n";0.56.1232339957368E-170A path on a map
<?nvs// Shows how a hiking app finds how long a sloped path is on a flat map.
class Trail{ // The length on the map is the real length times the cosine of the slope. public static function mapLength(float $meters, float $slopeDegrees): float { float $flat = $meters * Core\Math::cos(Core\Math::toRadians($slopeDegrees)); return Core\Math::round($flat, { precision: 1 }); }}
// A flat path of 100 meters is 100 meters on the map. This prints 100.echo Trail::mapLength(100.0, 0.0), "\n";
// The same path at a slope of 30 degrees is shorter on the map. This prints 86.6.echo Trail::mapLength(100.0, 30.0), "\n";
// A steep path of 250 meters at 45 degrees. This prints 176.8.echo Trail::mapLength(250.0, 45.0), "\n";10086.6176.8