motiejus/zig

fork of https://codeberg.org/ziglang/zig
git clone https://git.jakstys.lt/motiejus/zig.git
Log | Tree | Refs | README | LICENSE

commit 3e2e6c108a4306ed890b3034e2ad47c8d4caf2f7 (tree)
parent 6f55b294f60385b76187dbeac3d571449466ab3b
Author: frmdstryr <frmdstryr@protonmail.com>
Date:   Mon, 11 Jul 2022 09:40:05 -0400

std.math: add `degreesToRadians` and `radiansToDegrees`


Diffstat:
Mlib/std/math.zig | 28++++++++++++++++++++++++++++
1 file changed, 28 insertions(+), 0 deletions(-)

diff --git a/lib/std/math.zig b/lib/std/math.zig @@ -292,6 +292,34 @@ pub inline fn tan(value: anytype) @TypeOf(value) { return @tan(value); } +// Convert an angle in radians to degrees. T must be a float type. +pub fn radiansToDegrees(comptime T: type, angle_in_radians: T) T { + if (@typeInfo(T) != .Float) + @compileError("T must be a float type."); + return angle_in_radians * 180.0 / pi; +} + +test "radiansToDegrees" { + try std.testing.expectApproxEqAbs(@as(f32, 0), radiansToDegrees(f32, 0), 1e-6); + try std.testing.expectApproxEqAbs(@as(f32, 90), radiansToDegrees(f32, pi / 2.0), 1e-6); + try std.testing.expectApproxEqAbs(@as(f32, -45), radiansToDegrees(f32, -pi / 4.0), 1e-6); + try std.testing.expectApproxEqAbs(@as(f32, 180), radiansToDegrees(f32, pi), 1e-6); + try std.testing.expectApproxEqAbs(@as(f32, 360), radiansToDegrees(f32, 2.0 * pi), 1e-6); +} + +// Convert an angle in degrees to radians. T must be a float type. +pub fn degreesToRadians(comptime T: type, angle_in_degrees: T) T { + if (@typeInfo(T) != .Float) + @compileError("T must be a float type."); + return angle_in_degrees * pi / 180.0; +} + +test "degreesToRadians" { + try std.testing.expectApproxEqAbs(@as(f32, pi / 2.0), degreesToRadians(f32, 90), 1e-6); + try std.testing.expectApproxEqAbs(@as(f32, -3 * pi / 2.0), degreesToRadians(f32, -270), 1e-6); + try std.testing.expectApproxEqAbs(@as(f32, 2 * pi), degreesToRadians(f32, 360), 1e-6); +} + /// Base-e exponential function on a floating point number. /// Uses a dedicated hardware instruction when available. /// This is the same as calling the builtin @exp