aboutsummaryrefslogtreecommitdiffstats
path: root/test_ieee754.c
blob: 65d0aba996ac0ec736c7eb3f2c700fd33e14b4ad (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
/*
 * Copyright (C) 2018 Tomasz Kramkowski <tk@the-tk.com>
 * SPDX-License-Identifier: MIT
 */
#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>

#include "ieee754.h"

// naiive: return the binary representation of a float (non portable)
static unsigned long naiive(float n)
{
	union {
		float f;
		uint32_t u;
	} u = { .f = n };

	return u.u;
}

// test: test ieee754f against a certain number
void test(float a)
{
	float b = ieee754f(naiive(a));

	if (!((isnan(a) && isnan(b)) || a == b)) {
		fprintf(stderr, "%lu: %.40f != %.40f\n", naiive(a), a, b);
		exit(EXIT_FAILURE);
	}
}

int main(void)
{
	test(NAN);
	test(+INFINITY);
	test(-INFINITY);
	test(0x1p127f);
	test(0x7fffffp-149f);

	for (float n = -0.000000001; n <= 1; n = nextafterf(n, 2))
		test(n);
}