Sorry. 32-bit floats only.
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 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
| public final class FloatMath { private FloatMath() {}
private static final float EXP2_0 = 0xf.ffffep-4f; private static final float EXP2_1 = 0xb.1729ap-4f; private static final float EXP2_2 = 0x3.d79c1p-4f; private static final float EXP2_3 = 0xe.4d4cp-8f; private static final float EXP2_4 = 0x2.4a14p-8f; private static final float EXP2_5 = 0x7.c45p-12f; public static final float exp2(float x) { int a = (int)x; float b = x-a; float r = 0; r = b*(r + EXP2_5); r = b*(r + EXP2_4); r = b*(r + EXP2_3); r = b*(r + EXP2_2); r = b*(r + EXP2_1); r = (r + EXP2_0);
return exp2(a)*r; } private static final float LOG2_1 = 0x1.71547ap1f; private static final float LOG2_2 = 0x1.ec554ep-1f; private static final float LOG2_3 = 0x1.310a2cp-1f; public static final float log2(float x) { int i = Float.floatToRawIntBits(x); int e = ((i >>> 23) & 0xff)-127; float y = Float.intBitsToFloat(i - (e<<23)); float r = (y-sqrtOf2f)/(y+sqrtOf2f); float b = r * r; float a; a = r*(LOG2_1 + b*(LOG2_2 + b*LOG2_3)); return 0.5f + e + a; } private static final float oneOverLog2 = (float)(1.0/Math.log(2)); public static final float exp(float x) { return exp2(x * oneOverLog2); } public static final float powf(float x, float y) { return exp2(y * log2(x)); }
public static final float pow(float x, int n) { float r = 1.f; int e = n; if (n < 0) e = -n;
do { if ((e & 1) != 0) r *= x; e >>>= 1; if (e != 0) { x *= x; continue; } if (n >= 0) return r; return 1/r; } while(true); } private static final float sqrtOf2f = (float)Math.sqrt(2);
private static final float logOf2 = (float)Math.log(2); public static final float log(float x) { return log2(x) * logOf2; } private static final float log10Convert = 0x1.344136p-2f; public static final float log10(float x) { return log2(x) * log10Convert; } public static final float exp2(int x) { return Float.intBitsToFloat((x+127)<<23); }
} |