fixpoint.h
101 lines
| 1.9 KiB
| text/x-c
|
CLexer
|
r196 | /* | ||
* fixpoint<T>.h | ||||
* | ||||
* Created on: Feb 24, 2015 | ||||
* Author: aras | ||||
*/ | ||||
#ifndef FIXPOINT_H_ | ||||
#define FIXPOINT_H_ | ||||
#include <inttypes.h> | ||||
#include <math.h> | ||||
#include <typeinfo> | ||||
#include <cstdio> | ||||
typedef fixpoint<int32_t> fix19_12; | ||||
#define N43_20 fixpoint<int64_t> | ||||
#define N9_23 fixpoint<int32_t> | ||||
#define FAC64 20 | ||||
#define FAC32 12 | ||||
template<class T> | ||||
class fixpoint { | ||||
private: | ||||
uint8_t factor; | ||||
T value; | ||||
public: | ||||
fixpoint<T>(); | ||||
fixpoint<T>(T num); | ||||
void set_from_float(float num){value=T(num*(1<<factor));} | ||||
void set(T val){value = val;} | ||||
float tofloat(); | ||||
friend inline fixpoint<T> operator-(const fixpoint<T> &num1, const fixpoint<T> &num2){ | ||||
return fixpoint<T>(num1.value-num2.value); | ||||
} | ||||
friend inline fixpoint<T> operator+(const fixpoint<T> &num1, const fixpoint<T> &num2){ | ||||
return fixpoint<T>(num1.value+num2.value); | ||||
} | ||||
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>(aux); | ||||
} | ||||
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); | ||||
} | ||||
inline fixpoint<T> power(); | ||||
inline fixpoint<T> sqroot(); | ||||
}; | ||||
template<class T> | ||||
fixpoint<T>::fixpoint(){ | ||||
if(typeid(T)==typeid(int32_t)){ | ||||
factor=FAC32; | ||||
} | ||||
else{ | ||||
factor=FAC64; | ||||
} | ||||
value=0; | ||||
} | ||||
template<class T> | ||||
fixpoint<T>::fixpoint(T num){ | ||||
if(typeid(T)==typeid(int32_t)){ | ||||
factor=FAC32; | ||||
} | ||||
else{ | ||||
factor=FAC64; | ||||
} | ||||
value=num; | ||||
} | ||||
template<class T> | ||||
float fixpoint<T>::tofloat(){ | ||||
return float(value)/(1<<factor); | ||||
} | ||||
template<class T> | ||||
fixpoint<T> fixpoint<T>::power(){ | ||||
int64_t aux = (int64_t(value)*int64_t(value))>>factor; | ||||
return fixpoint<T>(aux); | ||||
} | ||||
template<class T> | ||||
fixpoint<T> fixpoint<T>::sqroot(){ | ||||
T aux = sqrt(value); | ||||
return fixpoint<T>(aux<<(factor/2)); | ||||
} | ||||
#endif /* FIXPOINT_H_ */ | ||||