backported more fixes from 256boss
[bootcensus] / src / libc / math.c
1 /*
2 pcboot - bootable PC demo/game kernel
3 Copyright (C) 2018-2019  John Tsiombikas <nuclear@member.fsf.org>
4
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, either version 3 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY, without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program.  If not, see <https://www.gnu.org/licenses/>.
17 */
18 #include "math.h"
19
20 static double calc_pow(double x, double y, double precision);
21
22 double pow(double x, double y)
23 {
24         if(y == 0.0 || y == -0.0) {
25                 return 1.0;
26         }
27         if(y == 1.0) {
28                 return x;
29         }
30         if(y == -INFINITY) {
31                 return fabs(x) < 1.0 ? INFINITY : 0.0;
32         }
33         if(y == INFINITY) {
34                 return fabs(x) < 1.0 ? 0.0 : INFINITY;
35         }
36         return calc_pow(x, y, 1e-6);
37 }
38
39 static double calc_pow(double x, double y, double precision)
40 {
41         if(y < 0.0) {
42                 return 1.0 / calc_pow(x, -y, precision);
43         }
44         if(y >= 10.0) {
45                 double p = calc_pow(x, y / 2.0, precision / 2.0);
46                 return p * p;
47         }
48         if(y >= 1.0) {
49                 return x * calc_pow(x, y - 1.0, precision);
50         }
51         if(precision >= 1) {
52                 return __builtin_sqrt(x);
53         }
54         return __builtin_sqrt(calc_pow(x, y * 2.0, precision * 2.0));
55 }