Skip to content

Commit 3e2e6c1

Browse files
authored
std.math: add degreesToRadians and radiansToDegrees
1 parent 6f55b29 commit 3e2e6c1

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

lib/std/math.zig

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -292,6 +292,34 @@ pub inline fn tan(value: anytype) @TypeOf(value) {
292292
return @tan(value);
293293
}
294294

295+
// Convert an angle in radians to degrees. T must be a float type.
296+
pub fn radiansToDegrees(comptime T: type, angle_in_radians: T) T {
297+
if (@typeInfo(T) != .Float)
298+
@compileError("T must be a float type.");
299+
return angle_in_radians * 180.0 / pi;
300+
}
301+
302+
test "radiansToDegrees" {
303+
try std.testing.expectApproxEqAbs(@as(f32, 0), radiansToDegrees(f32, 0), 1e-6);
304+
try std.testing.expectApproxEqAbs(@as(f32, 90), radiansToDegrees(f32, pi / 2.0), 1e-6);
305+
try std.testing.expectApproxEqAbs(@as(f32, -45), radiansToDegrees(f32, -pi / 4.0), 1e-6);
306+
try std.testing.expectApproxEqAbs(@as(f32, 180), radiansToDegrees(f32, pi), 1e-6);
307+
try std.testing.expectApproxEqAbs(@as(f32, 360), radiansToDegrees(f32, 2.0 * pi), 1e-6);
308+
}
309+
310+
// Convert an angle in degrees to radians. T must be a float type.
311+
pub fn degreesToRadians(comptime T: type, angle_in_degrees: T) T {
312+
if (@typeInfo(T) != .Float)
313+
@compileError("T must be a float type.");
314+
return angle_in_degrees * pi / 180.0;
315+
}
316+
317+
test "degreesToRadians" {
318+
try std.testing.expectApproxEqAbs(@as(f32, pi / 2.0), degreesToRadians(f32, 90), 1e-6);
319+
try std.testing.expectApproxEqAbs(@as(f32, -3 * pi / 2.0), degreesToRadians(f32, -270), 1e-6);
320+
try std.testing.expectApproxEqAbs(@as(f32, 2 * pi), degreesToRadians(f32, 360), 1e-6);
321+
}
322+
295323
/// Base-e exponential function on a floating point number.
296324
/// Uses a dedicated hardware instruction when available.
297325
/// This is the same as calling the builtin @exp

0 commit comments

Comments
 (0)