0.1.15 Fraction

This commit is contained in:
rob tillaart 2023-02-03 13:14:59 +01:00
parent da6be76692
commit cea234e035
13 changed files with 417 additions and 119 deletions

View File

@ -6,7 +6,7 @@ jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- uses: arduino/arduino-lint-action@v1
with:
library-manager: update

View File

@ -8,7 +8,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- uses: ruby/setup-ruby@v1
with:
ruby-version: 2.6

View File

@ -10,7 +10,7 @@ jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- name: json-syntax-check
uses: limitusus/json-syntax-check@v1
with:

View File

@ -6,12 +6,20 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/)
and this project adheres to [Semantic Versioning](http://semver.org/).
## [0.1.15] - 2023-02-02
- update GitHub actions
- update license 2023
- update readme.md
- move code to .cpp
- change signature **double toDouble()**
- add **Fraction_performance.ino** to start performance testing.
## [0.1.14] - 2022-11-07
- add changelog.md
- add rp2040 to build-CI
- update readme.md
## [0.1.13] - 2021-12-18
- update library.json
- update license
@ -30,40 +38,38 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
----
Long time ago ....
## [0.1.9]
## [0.1.9] - 2020-04-26
- refactor
## [0.1.8]
## [0.1.8] - 2018-04-02
- refactor made constructors explicit
- fix issue #33 double --> float
## [0.1.07]
## [0.1.07] - 2015-03-05
- major refactoring by Chris-A
## [0.1.06]
## [0.1.06] - 2015-02-15
- added proper(), mediant(), angle()
## [0.1.05]
## [0.1.05] - 2015-02-14
- tested negative Fractions math
- added constructors,
- minor refactoring
## [0.1.04]
## [0.1.04] - 2015-02-09
- stabilizing code
- add simplify() for some code paths.
## [0.1.03]
## [0.1.03] - 2015-02-07
- add toDouble()
- tested several fractionize() codes
- bug fixes.
## [0.1.02]
## [0.1.02] - 2015-02-07
- faster fractionize code
## [0.1.01]
## [0.1.01] - 2015-02-03
- some fixes
## [0.1.00]
## [0.1.00] - 2015-01-25
- initial version

View File

@ -1,6 +1,6 @@
MIT License
Copyright (c) 2015-2022 Rob Tillaart
Copyright (c) 2015-2023 Rob Tillaart
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal

View File

@ -0,0 +1,166 @@
//
// FILE: fractionTest01.ino
// AUTHOR: Rob Tillaart
// PURPOSE: test sketch for fraction math
// DATE: 2015-01-25
// URL: https://github.com/RobTillaart/Fraction
#include "fraction.h"
uint32_t start, stop;
void setup()
{
Serial.begin(115200);
Serial.println(__FILE__);
Serial.print("FRACTION_LIB_VERSION: ");
Serial.println(FRACTION_LIB_VERSION);
Serial.println();
test_constructor();
test_math();
test_conversion();
test_misc();
Serial.println("\ndone...");
}
void loop()
{
}
void test_constructor()
{
Serial.println();
Serial.println(__FUNCTION__);
delay(10);
start = micros();
Fraction q(0.42);
Fraction a(1, 3);
Fraction aa(3, 9);
Fraction b(1, 4);
Fraction n(0, 5);
Fraction p(5, 1);
Fraction pi(PI);
Fraction e(EULER);
stop = micros();
Serial.print("TIME: \t");
Serial.println(stop - start);
Serial.println(q);
Serial.println(a);
Serial.println(aa);
Serial.println(b);
Serial.println(n);
Serial.println(p);
Serial.println(pi);
Serial.println(e);
}
void test_math()
{
Serial.println();
Serial.println(__FUNCTION__);
delay(10);
Fraction a(0, 1);
Fraction pi(PI);
Fraction e(EULER);
start = micros();
a = pi + e;
stop = micros();
Serial.print("TIME +: \t");
Serial.println(stop - start);
Serial.println(a);
delay(10);
start = micros();
a = pi - e;
stop = micros();
Serial.print("TIME -: \t");
Serial.println(stop - start);
Serial.println(a);
delay(10);
start = micros();
a = pi * e;
stop = micros();
Serial.print("TIME *: \t");
Serial.println(stop - start);
Serial.println(a);
delay(10);
start = micros();
a = pi / e;
stop = micros();
Serial.print("TIME /: \t");
Serial.println(stop - start);
Serial.println(a);
}
void test_conversion()
{
Serial.println();
Serial.println(__FUNCTION__);
delay(10);
Fraction e(EULER);
double d;
start = micros();
d = e.toDouble();
stop = micros();
Serial.print("TIME toDouble(): \t");
Serial.println(stop - start);
Serial.println(d, 7);
delay(10);
start = micros();
d = e.toFloat();
stop = micros();
Serial.print("TIME toFloat(): \t");
Serial.println(stop - start);
Serial.println(d, 7);
delay(10);
start = micros();
d = e.toAngle();
stop = micros();
Serial.print("TIME toAngle(): \t");
Serial.println(stop - start);
Serial.println(d, 7);
}
void test_misc()
{
Serial.println();
Serial.println(__FUNCTION__);
delay(10);
Fraction a(0, 1);
Fraction pi(PI);
Fraction e(EULER);
start = micros();
a = Fraction::mediant(pi, e);
stop = micros();
Serial.print("TIME mediant(): \t");
Serial.println(stop - start);
Serial.println(a);
delay(10);
start = micros();
a = Fraction::middle(pi, e);
stop = micros();
Serial.print("TIME middle(): \t");
Serial.println(stop - start);
Serial.println(a);
}
// -- END OF FILE --

View File

@ -0,0 +1,43 @@
IDE 1.8.19
Arduino UNO
Fraction_performance.ino
FRACTION_LIB_VERSION: 0.1.15
test_constructor
TIME: 5288
21/50
1/3
1/3
1/4
0/1
5/1
355/113
3985/1466
test_math
TIME +: 1056
16179/2761
TIME -: 1444
701/1657
TIME *: 1204
23578/2761
TIME /: 1240
10409/9006
test_conversion
TIME toDouble(): 44
2.718281
TIME toFloat(): 40
2.718281
TIME toAngle(): 200
69.802467
test_misc
TIME mediant(): 372
4340/1579
TIME middle(): 1252
16179/5522
done...

View File

@ -1,11 +1,9 @@
//
// FILE: fraction.cpp
// AUTHOR: Rob Tillaart
// VERSION: 0.1.14
// PURPOSE: Arduino library to implement a Fraction datatype
// VERSION: 0.1.15
// PURPOSE: Arduino library to implement a Fraction data type
// URL: https://github.com/RobTillaart/Fraction
//
// HISTORY: see changelog.md
#include "fraction.h"
@ -13,7 +11,7 @@
//////////////////////////////////////
//
// CONSTRUCTORS
// CONSTRUCTORS
//
Fraction::Fraction(double d)
{
@ -29,14 +27,14 @@ Fraction::Fraction(float f)
void Fraction::split(float f)
{
// handle special cases?
// PI = 355/113; // 2.7e-7
// PI*2 = 710/113;
// PI/2 = 335/226;
// EULER = 2721/1001; // 1.1e-7
// EULER = 1264/465; // 2.2e-6
// handle special cases?
// PI = 355/113; // 2.7e-7
// PI*2 = 710/113;
// PI/2 = 335/226;
// EULER = 2721/1001; // 1.1e-7
// EULER = 1264/465; // 2.2e-6
// get robust for small values. (effectively zero)
// get robust for small values. (effectively zero)
if (abs(f) < 0.00001)
{
n = 0;
@ -53,11 +51,11 @@ void Fraction::split(float f)
bool negative = f < 0;
if (negative) f = -f;
// TODO investigate different strategy:
// intpart = int32_t(f); // strip of the integer part.
// f = f - intpart; // determine remainder
// determine n, d
// n += intpart * d; // add integer part * denominator to fraction.
// TODO investigate different strategy:
// intpart = int32_t(f); // strip of the integer part.
// f = f - intpart; // determine remainder
// determine n, d
// n += intpart * d; // add integer part * denominator to fraction.
bool reciproke = f > 1;
if (reciproke) f = 1/f;
@ -65,7 +63,7 @@ void Fraction::split(float f)
fractionize(f);
simplify();
// denormalize
// denormalize
if (reciproke)
{
int32_t t = n;
@ -87,12 +85,12 @@ Fraction::Fraction(int32_t p, int32_t q) : n(p), d(q)
//////////////////////////////////////
//
// PRINTING
// PRINTING
//
size_t Fraction::printTo(Print& p) const
{
size_t s = 0;
// TODO split of sign first
// TODO split of sign first
//
// vs 22/7 => 3_1/7
// if (n >= d)
@ -110,7 +108,7 @@ size_t Fraction::printTo(Print& p) const
//////////////////////////////////////
//
// EQUALITIES
// EQUALITIES
//
bool Fraction::operator == (const Fraction &c)
{
@ -156,7 +154,7 @@ bool Fraction::operator <= (const Fraction &c)
//////////////////////////////////////
//
// NEGATE
// NEGATE
//
Fraction Fraction::operator - ()
{
@ -166,7 +164,7 @@ Fraction Fraction::operator - ()
//////////////////////////////////////
//
// BASIC MATH
// BASIC MATH
//
Fraction Fraction::operator + (const Fraction &c)
{
@ -196,7 +194,7 @@ Fraction Fraction::operator * (const Fraction &c)
Fraction Fraction::operator / (const Fraction &c)
{
// division by zero returns 0
// division by zero returns 0
return Fraction(n * c.d, d * c.n);
}
@ -244,7 +242,7 @@ Fraction& Fraction::operator *= (const Fraction &c)
Fraction& Fraction::operator /= (const Fraction &c)
{
// division by zero returns 0
// division by zero returns 0
n *= c.d;
d *= c.n;
simplify();
@ -252,29 +250,47 @@ Fraction& Fraction::operator /= (const Fraction &c)
}
float Fraction::toDouble()
double Fraction::toDouble()
{
return (1.0 * n) / d;
return double(n) / d;
}
// fraction is proper if abs(fraction) < 1
float Fraction::toFloat()
{
return float(n) / d;
}
// fraction is proper if abs(fraction) < 1
bool Fraction::isProper()
{
return abs(n) < abs(d);
}
// visualize fraction as an angle in degrees
// visualize fraction as an angle in degrees
float Fraction::toAngle()
{
return atan2(n, d) * 180.0 / PI;
return atan2(n, d) * (180.0 / PI);
}
int32_t Fraction::nominator()
{
return n;
}
int32_t Fraction::denominator()
{
return d;
}
//////////////////////////////////////
//
// STATIC
// STATIC
//
// Mediant - http://www.cut-the-knot.org/Curriculum/Arithmetic/FCExercise.shtml
// void Fraction::mediant(Fraction c)
@ -285,24 +301,24 @@ float Fraction::toAngle()
// }
//
// the mediant is a fraction that is always between 2 fractions
// at least if within precision.
// the mediant is a fraction that is always between 2 fractions
// at least if within precision.
Fraction Fraction::mediant(const Fraction &a, const Fraction &b)
{
return Fraction(a.n + b.n, a.d + b.d);
}
// the middle is a fraction that is between 2 fractions
// at least if within precision.
// the middle is a fraction that is between 2 fractions
// at least if within precision.
Fraction Fraction::middle(const Fraction &a, const Fraction &b)
{
return Fraction(a.n*b.d + b.n*a.d, 2 * a.d * b.d);
}
// approximate a fraction with defined denominator
// sort of setDenominator(uint16_t den);
// approximate a fraction with defined denominator
// sort of setDenominator(uint16_t den);
Fraction Fraction::setDenominator(const Fraction &a, uint16_t b)
{
int32_t n = round((a.n * b * 1.0) / a.d);
@ -313,8 +329,8 @@ Fraction Fraction::setDenominator(const Fraction &a, uint16_t b)
//////////////////////////////////////
//
// PRIVATE
// http://en.wikipedia.org/wiki/Binary_GCD_algorithm
// PROTECTED
// http://en.wikipedia.org/wiki/Binary_GCD_algorithm
//
int32_t Fraction::gcd(int32_t a , int32_t b)
{
@ -328,7 +344,7 @@ int32_t Fraction::gcd(int32_t a , int32_t b)
}
// not that simple ...
// not that simple ...
void Fraction::simplify()
{
if (n == 0)
@ -343,11 +359,11 @@ void Fraction::simplify()
p = p / x;
q = q / x;
// denominator max 4 digits keeps mul and div simple
// in preventing overflow
// denominator max 4 digits keeps mul and div simple
// in preventing overflow
while (q > 10000)
{
// rounding might need improvement
// rounding might need improvement
p = (p + 5)/10;
q = (q + 5)/10;
x = gcd(p, q);
@ -361,24 +377,24 @@ void Fraction::simplify()
//////////////////////////////////////////////////////////////////////////////
//
// fractionize() - finds the fraction representation of a float
// PRE: 0 <= f < 1.0
// fractionize() - finds the fraction representation of a float
// PRE: 0 <= f < 1.0
//
// minimalistic is fast and small
// minimalistic is fast and small
//
// check for a discussion found later
// - http://mathforum.org/library/drmath/view/51886.html
// - http://www.gamedev.net/topic/354209-how-do-i-convert-a-decimal-to-a-fraction-in-c/
// check for a discussion found later
// - http://mathforum.org/library/drmath/view/51886.html
// - http://www.gamedev.net/topic/354209-how-do-i-convert-a-decimal-to-a-fraction-in-c/
//
// Dr. Peterson
// - http://mathforum.org/library/drmath/view/51886.html
// (100x) micros()=96048
// showed errors for very small values around 0
// Dr. Peterson
// - http://mathforum.org/library/drmath/view/51886.html
// (100x) micros()=96048
// showed errors for very small values around 0
void Fraction::fractionize(float val)
{
// find nearest fraction
// find nearest fraction
float Precision = 0.0000001;
Fraction low(0, 1); // "A" = 0/1
Fraction high(1, 1); // "B" = 1/1
@ -387,36 +403,36 @@ void Fraction::fractionize(float val)
float testLow = low.d * val - low.n;
float testHigh = high.n - high.d * val;
if (testHigh < Precision * high.d)
break; // high is answer
break; // high is answer
if (testLow < Precision * low.d)
{ // low is answer
{ // low is answer
high = low;
break;
}
if (i & 1)
{ // odd step: add multiple of low to high
{ // odd step: add multiple of low to high
float test = testHigh / testLow;
int32_t count = (int32_t)test; // "N"
int32_t count = (int32_t)test; // "N"
int32_t n = (count + 1) * low.n + high.n;
int32_t d = (count + 1) * low.d + high.d;
if ((n > 0x8000) || (d > 0x10000))
break;
high.n = n - low.n; // new "A"
high.n = n - low.n; // new "A"
high.d = d - low.d;
low.n = n; // new "B"
low.n = n; // new "B"
low.d = d;
}
else
{ // even step: add multiple of high to low
{ // even step: add multiple of high to low
float test = testLow / testHigh;
int32_t count = (int32_t)test; // "N"
int32_t count = (int32_t)test; // "N"
int32_t n = low.n + (count + 1) * high.n;
int32_t d = low.d + (count + 1) * high.d;
if ((n > 0x10000) || (d > 0x10000))
break;
low.n = n - high.n; // new "A"
low.n = n - high.n; // new "A"
low.d = d - high.d;
high.n = n; // new "B"
high.n = n; // new "B"
high.d = d;
}
}
@ -425,5 +441,5 @@ void Fraction::fractionize(float val)
}
// -- END OF FILE --
// -- END OF FILE --

View File

@ -2,15 +2,15 @@
//
// FILE: fraction.h
// AUTHOR: Rob Tillaart
// VERSION: 0.1.14
// PURPOSE: Arduino library to implement a Fraction datatype
// VERSION: 0.1.15
// PURPOSE: Arduino library to implement a Fraction data type
// URL: https://github.com/RobTillaart/Fraction
//
#include "Arduino.h"
#define FRACTION_LIB_VERSION (F("0.1.14"))
#define FRACTION_LIB_VERSION (F("0.1.15"))
class Fraction: public Printable
@ -20,6 +20,7 @@ public:
explicit Fraction(float);
Fraction(int32_t, int32_t);
// CONSTRUCTORS
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) {}
@ -30,19 +31,19 @@ public:
size_t printTo(Print& p) const;
// equalities
// EQUALITIES
bool operator == (const Fraction&);
// bool operator == (const float&);
// bool operator == (const float&);
bool operator != (const Fraction&);
bool operator > (const Fraction&);
bool operator >= (const Fraction&);
bool operator < (const Fraction&);
bool operator <= (const Fraction&);
// negation
// NEGATE
Fraction operator - ();
// basic maths
// BASIC MATH
Fraction operator + (const Fraction&);
Fraction operator - (const Fraction&);
Fraction operator * (const Fraction&);
@ -53,22 +54,20 @@ public:
Fraction& operator *= (const Fraction&);
Fraction& operator /= (const Fraction&);
float toDouble();
float toFloat() { return toDouble(); };
bool isProper(); // abs(f) < 1
// CONVERSION
double toDouble();
float toFloat();
bool isProper(); // abs(f) < 1
float toAngle();
int32_t nominator();
int32_t denominator();
int32_t nominator() { return n; };
int32_t denominator() { return d; };
// MISCELLANEOUS (static)
static Fraction mediant(const Fraction&, const Fraction&);
static Fraction middle(const Fraction&, const Fraction&);
// approximate a fraction with defined denominator
// approximate a fraction with defined denominator
static Fraction setDenominator(const Fraction&, uint16_t);
@ -83,4 +82,4 @@ protected:
};
// -- END OF FILE --
// -- END OF FILE --

View File

@ -15,7 +15,7 @@
"type": "git",
"url": "https://github.com/RobTillaart/Fraction.git"
},
"version": "0.1.14",
"version": "0.1.15",
"frameworks": "arduino",
"platforms": "*",
"headers": "fraction.h"

View File

@ -1,5 +1,5 @@
name=Fraction
version=0.1.14
version=0.1.15
author=Rob Tillaart <rob.tillaart@gmail.com>
maintainer=Rob Tillaart <rob.tillaart@gmail.com>
sentence=Arduino library to implement a Fraction datatype

View File

@ -14,44 +14,109 @@ Arduino library to implement a Fraction data type (experimental).
## Description
The fraction library implements fractional numbers a.k.a. Q,
(integers are Z and floats/doubles are R),
and the conversion to floats.
(integers are Z and floats/doubles are R), and the conversion to floats.
The code is working with a number of limitations among others:
The code is working with a number of limitations a.o.:
- denominator is max 4 digits to keep code for multiply and divide simple
- Fractions are not exact (even floats are not exact)
- Fractions are not exact, even floats are not exact.
- the range of numbers supported is limited.
- code is experimental still.
That said, the library is useful e.g. to display float numbers as a fraction.
From programming point of view the **fractionize()** function, converting a double
From programming point of view the **fractionize(float)** function, converting a double
into a fraction is a nice programming problem, fast with a minimal error.
In short, use fractions with care otherwise your sketch might get broken ;)
## Operations
## Interface
See examples
```cpp
#include "fraction.h"
```
#### Constructors
- **explicit Fraction(double)**
- **explicit Fraction(float)**
- **Fraction(int32_t nominator, int32_t denominator)**
- **explicit Fraction(int32_t p)**
- **explicit Fraction(int16_t p)**
- **explicit Fraction(int8_t p)**
- **explicit Fraction(uint32_t p)**
- **explicit Fraction(uint16_t p)**
- **explicit Fraction(uint8_t p)**
- **Fraction(const Fraction &f)**
#### Printable
The Fraction library implements Printable, so one can do.
```cpp
Fraction fr(PI);
Serial.print(fr); // print 355/113
```
#### Equalities
The Fraction library implements ==, !=, >=, >, <, <=
#### Basic Math
The Fraction library implements, + - * / += -= *= /= and - (negation)
#### Conversion
- **double toDouble()** idem.
- **float toFloat()** idem.
- **bool isProper()** absolute value < 1.
- **float toAngle()** returns 0..360 degrees.
- **int32_t nominator()** idem.
- **int32_t denominator()** idem.
#### Miscellaneous (static)
- **Fraction mediant(const Fraction&, const Fraction&)**
- **Fraction middle(const Fraction&, const Fraction&)**
- **Fraction setDenominator(const Fraction&, uint16_t)**
## Use with care
The library is reasonably tested, and if problems arise please let me know.
The library is reasonably tested. If problems arise please open an issue.
## Future
#### must
#### Must
- improve documentation
- test test test ...
#### should
- investigate divide by zero errors
- investigate better fractionize() - depends on nom/denom size
#### Should
- performance testing
- investigate divide by zero errors
- NAN in fraction? => 0/0 ?
- INF in fraction? => 1/0 and -1/0?
- investigate better **fractionize()**
- depends on nom/denom size
- returns the error..
#### Could
#### could
- extend unit tests
- experiment with bigger nominator/denominator using all of 32767 possibilities ?
- add famous constants as Fraction e.g FRAC_PI = (355, 113) ??
- add famous constants as Fraction e.g
- FRAC_PI = 355/113
- FRAC_E = 3985/1466
#### Wont

View File

@ -35,6 +35,7 @@ unittest_setup()
fprintf(stderr, "FRACTION_LIB_VERSION: %s\n", (char*) FRACTION_LIB_VERSION);
}
unittest_teardown()
{
}
@ -82,11 +83,13 @@ unittest(test_math)
{
Fraction pi(PI);
Fraction ee(EULER);
// TODO
// TODO
assertEqual(1, 1);
}
unittest_main()
// --------
// -- END OF FILE --