2017-12-24 03:08:53 +00:00
|
|
|
const std = @import("../index.zig");
|
|
|
|
const math = std.math;
|
|
|
|
const assert = std.debug.assert;
|
2017-06-16 09:26:10 +01:00
|
|
|
|
2018-01-25 09:10:11 +00:00
|
|
|
pub fn scalbn(x: var, n: i32) @typeOf(x) {
|
2017-06-16 09:26:10 +01:00
|
|
|
const T = @typeOf(x);
|
2017-12-22 05:50:30 +00:00
|
|
|
return switch (T) {
|
2017-12-22 18:14:07 +00:00
|
|
|
f32 => scalbn32(x, n),
|
|
|
|
f64 => scalbn64(x, n),
|
2017-06-16 09:26:10 +01:00
|
|
|
else => @compileError("scalbn not implemented for " ++ @typeName(T)),
|
2017-12-22 05:50:30 +00:00
|
|
|
};
|
2017-06-16 09:26:10 +01:00
|
|
|
}
|
|
|
|
|
2018-01-25 09:10:11 +00:00
|
|
|
fn scalbn32(x: f32, n_: i32) f32 {
|
2017-06-16 09:26:10 +01:00
|
|
|
var y = x;
|
|
|
|
var n = n_;
|
|
|
|
|
|
|
|
if (n > 127) {
|
|
|
|
y *= 0x1.0p127;
|
|
|
|
n -= 127;
|
|
|
|
if (n > 1023) {
|
|
|
|
y *= 0x1.0p127;
|
|
|
|
n -= 127;
|
|
|
|
if (n > 127) {
|
|
|
|
n = 127;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
} else if (n < -126) {
|
|
|
|
y *= 0x1.0p-126 * 0x1.0p24;
|
|
|
|
n += 126 - 24;
|
|
|
|
if (n < -126) {
|
|
|
|
y *= 0x1.0p-126 * 0x1.0p24;
|
|
|
|
n += 126 - 24;
|
|
|
|
if (n < -126) {
|
|
|
|
n = -126;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
const u = u32(n +% 0x7F) << 23;
|
2017-12-22 05:50:30 +00:00
|
|
|
return y * @bitCast(f32, u);
|
2017-06-16 09:26:10 +01:00
|
|
|
}
|
|
|
|
|
2018-01-25 09:10:11 +00:00
|
|
|
fn scalbn64(x: f64, n_: i32) f64 {
|
2017-06-16 09:26:10 +01:00
|
|
|
var y = x;
|
|
|
|
var n = n_;
|
|
|
|
|
|
|
|
if (n > 1023) {
|
2017-09-28 07:15:06 +01:00
|
|
|
y *= 0x1.0p1023;
|
2017-06-16 09:26:10 +01:00
|
|
|
n -= 1023;
|
|
|
|
if (n > 1023) {
|
2017-09-28 07:15:06 +01:00
|
|
|
y *= 0x1.0p1023;
|
2017-06-16 09:26:10 +01:00
|
|
|
n -= 1023;
|
|
|
|
if (n > 1023) {
|
|
|
|
n = 1023;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
} else if (n < -1022) {
|
|
|
|
y *= 0x1.0p-1022 * 0x1.0p53;
|
|
|
|
n += 1022 - 53;
|
|
|
|
if (n < -1022) {
|
|
|
|
y *= 0x1.0p-1022 * 0x1.0p53;
|
|
|
|
n += 1022 - 53;
|
|
|
|
if (n < -1022) {
|
|
|
|
n = -1022;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
const u = u64(n +% 0x3FF) << 52;
|
2017-12-22 05:50:30 +00:00
|
|
|
return y * @bitCast(f64, u);
|
2017-06-16 09:26:10 +01:00
|
|
|
}
|
|
|
|
|
2017-06-19 19:36:33 +01:00
|
|
|
test "math.scalbn" {
|
2017-06-16 09:26:10 +01:00
|
|
|
assert(scalbn(f32(1.5), 4) == scalbn32(1.5, 4));
|
|
|
|
assert(scalbn(f64(1.5), 4) == scalbn64(1.5, 4));
|
|
|
|
}
|
|
|
|
|
2017-06-19 19:36:33 +01:00
|
|
|
test "math.scalbn32" {
|
2017-06-16 09:26:10 +01:00
|
|
|
assert(scalbn32(1.5, 4) == 24.0);
|
|
|
|
}
|
|
|
|
|
2017-06-19 19:36:33 +01:00
|
|
|
test "math.scalbn64" {
|
2017-06-16 09:26:10 +01:00
|
|
|
assert(scalbn64(1.5, 4) == 24.0);
|
|
|
|
}
|