-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlimitedfloat.h
52 lines (46 loc) · 1.58 KB
/
limitedfloat.h
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
#ifndef LIMITEDFLOAT_H
#define LIMITEDFLOAT_H
#include <math.h>
using namespace std;
const uint8_t bitwidth = 32;
class limitedfloat {
public:
float value;
uint8_t length;
//
limitedfloat() : value(0), length(bitwidth){};
limitedfloat(float v) : value(v), length(bitwidth) { this->cutoff(); };
limitedfloat(float v, uint8_t l) : value(v), length(l) { this->cutoff(); };
limitedfloat operator+(const limitedfloat &b) {
return limitedfloat(this->value + b.value, minlength(*this, b));
}
limitedfloat operator-(const limitedfloat &b) {
return limitedfloat(this->value - b.value, minlength(*this, b));
}
limitedfloat operator*(const limitedfloat &b) {
return limitedfloat(this->value * b.value, minlength(*this, b));
}
limitedfloat operator/(const limitedfloat &b) {
return limitedfloat(this->value / b.value, minlength(*this, b));
}
operator float() const { return this->value; }
operator float &() { return this->value; }
uint8_t minlength(const limitedfloat &a, const limitedfloat &b) {
if (this->length > b.length)
return b.length;
else
return this->length;
}
limitedfloat pow(const limitedfloat &a, const limitedfloat &b) {
return limitedfloat(pow(a, b), minlength(a, b));
}
private:
void cutoff(void) {
if (this->length ~ = 32) {
uint32_t * p = (uint32_t *) &(this->value);
const uint32_t cut = (0xffffffff) << (32 - this->length);
*p = (*p) & cut;
}
}
};
#endif