fixpoint.h
102 lines
| 1.9 KiB
| text/x-c
|
CLexer
|
r202 | /* | ||
* fixpoint<T>.h | ||||
* | ||||
* Created on: Feb 24, 2015 | ||||
* Author: aras | ||||
*/ | ||||
#ifndef FIXPOINT_H_ | ||||
#define FIXPOINT_H_ | ||||
#include <inttypes.h> | ||||
#include <math.h> | ||||
|
r203 | typedef int32_t f1120; | ||
typedef int64_t f4320; | ||||
|
r202 | |||
template<class T> | ||||
class fixpoint { | ||||
private: | ||||
|
r203 | const uint8_t factor; | ||
|
r202 | T value; | ||
public: | ||||
|
r203 | fixpoint<T>(); | ||
fixpoint<T>(const fixpoint<T>& fp) : | ||||
factor(20) { | ||||
fixpoint<T>(); | ||||
value = fp.value; | ||||
} | ||||
; | ||||
fixpoint<T>(T num); | ||||
|
r202 | |||
|
r203 | void set_from_float(float num) { | ||
value = T(num * (1 << factor)); | ||||
} | ||||
void set(T val) { | ||||
value = val; | ||||
} | ||||
|
r202 | float tofloat(); | ||
|
r203 | friend inline fixpoint<T> operator-(const fixpoint<T> &num1, | ||
const fixpoint<T> &num2) { | ||||
return fixpoint<T>(num1.value - num2.value); | ||||
|
r202 | } | ||
|
r203 | friend inline fixpoint<T> operator+(const fixpoint<T> &num1, | ||
const fixpoint<T> &num2) { | ||||
return fixpoint<T>(num1.value + num2.value); | ||||
|
r202 | } | ||
|
r203 | friend inline fixpoint<T> operator*(const fixpoint<T> &num1, | ||
const fixpoint<T> &num2) { | ||||
int64_t aux = (int64_t(num1.value) * int64_t(num2.value)) | ||||
>> num1.factor; | ||||
return fixpoint<T>(T(aux)); | ||||
|
r202 | } | ||
|
r203 | friend inline fixpoint<T> operator/(const fixpoint<T> &num1, | ||
const fixpoint<T> &num2) { | ||||
int64_t aux = (int64_t(num1.value) << num1.factor); | ||||
return fixpoint<T>(aux / num2.value); | ||||
|
r202 | } | ||
|
r203 | inline fixpoint<T>& operator=(const fixpoint<T> &num) { | ||
value = num.value; | ||||
return *this; | ||||
} | ||||
|
r202 | |||
inline fixpoint<T> power(); | ||||
inline fixpoint<T> sqroot(); | ||||
}; | ||||
template<class T> | ||||
|
r203 | fixpoint<T>::fixpoint() : | ||
factor(20) { | ||||
value = 0; | ||||
|
r202 | } | ||
template<class T> | ||||
|
r203 | fixpoint<T>::fixpoint(T num) : | ||
factor(20) { | ||||
value = num; | ||||
|
r202 | } | ||
template<class T> | ||||
|
r203 | float fixpoint<T>::tofloat() { | ||
return float(value) / (1 << factor); | ||||
|
r202 | } | ||
template<class T> | ||||
|
r203 | fixpoint<T> fixpoint<T>::power() { | ||
int64_t aux = (int64_t(value) * int64_t(value)) >> factor; | ||||
|
r202 | return fixpoint<T>(aux); | ||
} | ||||
template<class T> | ||||
|
r203 | fixpoint<T> fixpoint<T>::sqroot() { | ||
|
r202 | T aux = sqrt(value); | ||
|
r203 | return fixpoint<T>(aux << (factor / 2)); | ||
|
r202 | } | ||
|
r203 | #define fix64 fixpoint<f4320> | ||
#define fix32 fixpoint<f1120> | ||||
|
r202 | |||
#endif /* FIXPOINT_H_ */ | ||||