aboutsummaryrefslogtreecommitdiff
path: root/std/math/isinf.zig
blob: a976fb73d24c47f18d2430d5e78c443cbb537851 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
const std = @import("../index.zig");
const math = std.math;
const assert = std.debug.assert;

pub fn isInf(x: var) bool {
    const T = @typeOf(x);
    switch (T) {
        f32 => {
            const bits = @bitCast(u32, x);
            return bits & 0x7FFFFFFF == 0x7F800000;
        },
        f64 => {
            const bits = @bitCast(u64, x);
            return bits & (@maxValue(u64) >> 1) == (0x7FF << 52);
        },
        else => {
            @compileError("isInf not implemented for " ++ @typeName(T));
        },
    }
}

pub fn isPositiveInf(x: var) bool {
    const T = @typeOf(x);
    switch (T) {
        f32 => {
            return @bitCast(u32, x) == 0x7F800000;
        },
        f64 => {
            return @bitCast(u64, x) == 0x7FF << 52;
        },
        else => {
            @compileError("isPositiveInf not implemented for " ++ @typeName(T));
        },
    }
}

pub fn isNegativeInf(x: var) bool {
    const T = @typeOf(x);
    switch (T) {
        f32 => {
            return @bitCast(u32, x) == 0xFF800000;
        },
        f64 => {
            return @bitCast(u64, x) == 0xFFF << 52;
        },
        else => {
            @compileError("isNegativeInf not implemented for " ++ @typeName(T));
        },
    }
}

test "math.isInf" {
    assert(!isInf(f32(0.0)));
    assert(!isInf(f32(-0.0)));
    assert(!isInf(f64(0.0)));
    assert(!isInf(f64(-0.0)));
    assert(isInf(math.inf(f32)));
    assert(isInf(-math.inf(f32)));
    assert(isInf(math.inf(f64)));
    assert(isInf(-math.inf(f64)));
}

test "math.isPositiveInf" {
    assert(!isPositiveInf(f32(0.0)));
    assert(!isPositiveInf(f32(-0.0)));
    assert(!isPositiveInf(f64(0.0)));
    assert(!isPositiveInf(f64(-0.0)));
    assert(isPositiveInf(math.inf(f32)));
    assert(!isPositiveInf(-math.inf(f32)));
    assert(isPositiveInf(math.inf(f64)));
    assert(!isPositiveInf(-math.inf(f64)));
}

test "math.isNegativeInf" {
    assert(!isNegativeInf(f32(0.0)));
    assert(!isNegativeInf(f32(-0.0)));
    assert(!isNegativeInf(f64(0.0)));
    assert(!isNegativeInf(f64(-0.0)));
    assert(!isNegativeInf(math.inf(f32)));
    assert(isNegativeInf(-math.inf(f32)));
    assert(!isNegativeInf(math.inf(f64)));
    assert(isNegativeInf(-math.inf(f64)));
}