87 lines
2.1 KiB
C
Raw Normal View History

2020-11-27 11:16:22 +01:00
#pragma once
2015-03-01 12:03:22 +01:00
//
// FILE: fraction.h
// AUTHOR: Rob Tillaart
2021-12-18 14:10:11 +01:00
// VERSION: 0.1.13
// PURPOSE: Arduino library to implement a Fraction datatype
2020-11-27 11:16:22 +01:00
// URL: https://github.com/RobTillaart/Fraction
2015-03-01 12:03:22 +01:00
//
2021-11-01 15:56:22 +01:00
2015-03-01 12:03:22 +01:00
#include "Arduino.h"
2021-12-18 14:10:11 +01:00
#define FRACTION_LIB_VERSION (F("0.1.13"))
2021-11-01 15:56:22 +01:00
2015-03-01 12:03:22 +01:00
class Fraction: public Printable
{
public:
explicit Fraction(double);
explicit Fraction(float);
2015-03-01 12:03:22 +01:00
Fraction(int32_t, int32_t);
2021-11-01 15:56:22 +01:00
explicit Fraction(int32_t p) : n(p), d(1) {}
explicit Fraction(int16_t p) : n(p), d(1) {}
explicit Fraction(int8_t p) : n(p), d(1) {}
explicit Fraction(uint32_t p) : n(p), d(1) {}
explicit Fraction(uint16_t p) : n(p), d(1) {}
explicit Fraction(uint8_t p) : n(p), d(1) {}
2015-03-05 18:26:06 +01:00
Fraction(const Fraction &f) : n(f.n), d(f.d) {}
2015-03-01 12:03:22 +01:00
size_t printTo(Print& p) const;
// equalities
2015-03-05 17:42:23 +10:00
bool operator == (const Fraction&);
2020-11-27 11:16:22 +01:00
// bool operator == (const float&);
2015-03-05 17:42:23 +10:00
bool operator != (const Fraction&);
bool operator > (const Fraction&);
bool operator >= (const Fraction&);
bool operator < (const Fraction&);
bool operator <= (const Fraction&);
2015-03-01 12:03:22 +01:00
// negation
Fraction operator - ();
2015-03-01 12:03:22 +01:00
2021-11-01 15:56:22 +01:00
// basic maths
2015-03-05 17:42:23 +10:00
Fraction operator + (const Fraction&);
Fraction operator - (const Fraction&);
Fraction operator * (const Fraction&);
Fraction operator / (const Fraction&);
2015-03-01 12:03:22 +01:00
2015-03-05 17:42:23 +10:00
Fraction& operator += (const Fraction&);
Fraction& operator -= (const Fraction&);
Fraction& operator *= (const Fraction&);
Fraction& operator /= (const Fraction&);
2015-03-01 12:03:22 +01:00
2021-11-01 15:56:22 +01:00
float toDouble();
float toFloat() { return toDouble(); };
bool isProper(); // abs(f) < 1
float toAngle();
2021-11-01 15:56:22 +01:00
2020-11-27 11:16:22 +01:00
int32_t nominator() { return n; };
int32_t denominator() { return d; };
2021-01-29 12:31:58 +01:00
2021-11-01 15:56:22 +01:00
static Fraction mediant(const Fraction&, const Fraction&);
2020-11-27 11:16:22 +01:00
static Fraction middle(const Fraction&, const Fraction&);
2021-11-01 15:56:22 +01:00
// approximate a fraction with defined denominator
static Fraction setDenominator(const Fraction&, uint16_t);
protected:
void split(float);
void simplify();
void fractionize(float);
2015-03-05 18:29:58 +10:00
int32_t gcd(int32_t, int32_t);
2015-03-01 12:03:22 +01:00
int32_t n;
int32_t d;
};
2021-11-01 15:56:22 +01:00
// -- END OF FILE --