basic routines for ContFrac

This commit is contained in:
2022-02-18 16:10:31 +01:00
parent 5544ea4ee7
commit 10985a146b
4 changed files with 178 additions and 3 deletions

View File

@@ -25,17 +25,45 @@
namespace LA {
//simple finite continued fraction class
//NOTE: 0 on any position >0 means actually infinity; simplify() shortens the vector
//presently implements just conversion to/from rationals and floats
//maybe implement arithmetic by Gosper's method cf. https://perl.plover.com/classes/cftalk/TALK
template <typename T>
class Rational {
public:
T num;
T den;
Rational(const T p, const T q) : num(p),den(q) {};
};
template <typename T>
class ContFrac : public NRVec<T> {
private:
int size() const; //prevent confusion with vector size
public:
ContFrac(): NRVec<T>() {};
template<int SIZE> ContFrac(const T (&a)[SIZE]) : NRVec<T>(a) {};
ContFrac(const NRVec<T> &v) : NRVec<T>(v) {}; //allow implicit conversion from NRVec
ContFrac(const int n) : NRVec<T>(n+1) {};
ContFrac(double x, const int n, const T thres=0); //might yield a non-canonical form
ContFrac(const T p, const T q); //should yield a canonical form
ContFrac(const Rational<T> r) : ContFrac(r.num,r.den) {};
void canonicalize();
void convergent(T *p, T*q, const int trunc= -1) const;
Rational<T> rational(const int trunc= -1) const {T p,q; convergent(&p,&q,trunc); return Rational<T>(p,q);};
double value(const int trunc= -1) const;
ContFrac reciprocal() const;
int length() const {return NRVec<T>::size()-1;};
void resize(const int n, const bool preserve=true) {NRVec<T>::resize(n+1,preserve);}
void resize(const int n, const bool preserve=true)
{
int nold=length();
NRVec<T>::resize(n+1,preserve);
if(preserve) for(int i=nold+1; i<=n;++i) (*this)[i]=0;
}
};