Skip to content

Commit fffa458

Browse files
committed
Added example on Inverses
1 parent f8d2166 commit fffa458

1 file changed

Lines changed: 71 additions & 0 deletions

File tree

examples/Inverses/Inverses.ino

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
/*
2+
* FixMath Library - Example demonstrating the different inverse functions and their limitations.
3+
*
4+
* This example code is in the public domain CONTRARY TO THE LIBRARY itself,
5+
* which is licensed the GNU Lesser General Public Licence
6+
*
7+
*/
8+
9+
10+
11+
#include <FixMath.h>
12+
13+
UFix<8, 8> a = 250.5;
14+
UFix<8, 8> b = 150.2;
15+
16+
void setup() {
17+
Serial.begin(9600);
18+
}
19+
20+
void loop() {
21+
22+
/*
23+
invFast() is able to represent the whole range
24+
of inverses of a number (ie. minimum and maximum will be approximately correct)
25+
but not accurately. This is shown here as two very different numbers
26+
have the same inverse). For a Fix<NI,NF> the invFast is of type Fix<NF,NI>
27+
*/
28+
Serial.print(a.asFloat());
29+
Serial.print(".invFast()=");
30+
Serial.println(a.invFast().asFloat(), 10);
31+
32+
Serial.print(b.asFloat());
33+
Serial.print(".invFast()=");
34+
Serial.println(b.invFast().asFloat(), 10);
35+
36+
37+
/*
38+
invAccurate provides a better resolution but the output type is
39+
way bigger: Fix<NI,NF>.invAccurate() is a Fix<2*NF+NI,NI>.
40+
In most case, this provides different values for every
41+
different number.
42+
Here, the resulting numbers are UFix<8,24>.
43+
*/
44+
Serial.print(a.asFloat());
45+
Serial.print(".invAccurate()=");
46+
Serial.println(a.invAccurate().asFloat(), 10);
47+
48+
Serial.print(b.asFloat());
49+
Serial.print(".invAccurate()=");
50+
Serial.println(b.invAccurate().asFloat(), 10);
51+
52+
/*
53+
An intermediate solution is provided by .inv<_NF>(),
54+
where the number of fractional bits is specified.
55+
This allows for optimization over .invAccurate()
56+
when needed.
57+
*/
58+
Serial.print(a.asFloat());
59+
Serial.print(".inv<12>()=");
60+
Serial.println(a.inv<12>().asFloat(), 10);
61+
62+
Serial.print(b.asFloat());
63+
Serial.print(".inv<12>()=");
64+
Serial.println(b.inv<12>().asFloat(), 10);
65+
66+
Serial.println();
67+
Serial.println();
68+
69+
70+
delay(10000);
71+
}

0 commit comments

Comments
 (0)