NewLinuxFan
Well-known member
I noticed that the Teensy 4.0 and 4.1 have a special processor for floating point math. With Arduinos I remember that it was always faster to use integer math, but does it really matter with the Teensy 4's? Sometimes C libraries that do advanced numerical analysis are commonly available in floating point, and it would be extra coding work to adapt them to integer math while being aware of potential rollover and truncation issues. Even correcting Arduino's map function to get even spacing is much simpler using floating point than writing more advanced map functions that use integer math. Do we need to bother with tedious integer coding with the newer more advanced Teensy's? Some people might say it's easy (maybe for you it is), but I think dealing with that stuff sucks and distracts my focus from the projects that I'm working on.
As an example, here's 3 improvements on the map function, copied from the Arduino forum:
As an example, here's 3 improvements on the map function, copied from the Arduino forum:
C++:
float floatMap(float x, float in_min, float in_max, float out_min, float out_max) // just switching longs with floats
{
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}
long idealMap(long x, long in_min, long in_max, long out_min, long out_max) // written by PJRC
{
long in_range = in_max - in_min;
long out_range = out_max - out_min;
if (in_range == 0) return out_min + out_range / 2;
// compute the numerator
long num = (x - in_min) * out_range;
// before dividing, add extra for proper round off (towards zero)
if (out_range >= 0)
{
num += in_range / 2;
} else
{
num -= in_range / 2;
}
// divide by input range and add output offset to complete map() compute
long result = num / in_range + out_min;
// fix "a strange behaviour with negative numbers" (see ArduinoCore-API issue #51)
// this step can be deleted if you don't care about non-linear output
// behavior extrapolating slightly beyond the mapped input & output range
if (out_range >= 0)
{
if (in_range * num < 0) return result - 1;
} else {
if (in_range * num >= 0) return result + 1;
}
return result;
}
long ifloor(long n, long d)
{
return ((n % d) < 0L) ? (n / d - 1) : n / d;
}
long mapIntervals(long x, long in_min, long in_max, long out_min, long out_max) // written by Phoenix Williams
{
if (in_min == in_max) return 0x7FFFFFFF; // slope is infinite; return max (long)
long x1, x2, y1, y2;
if (((in_max - in_min) < 0) != ((out_max - out_min) < 0)) {
// Slope is negative
x1 = min(in_min, in_max) - 1;
x2 = max(in_min, in_max);
y1 = max(out_min, out_max) + 1;
y2 = min(out_min, out_max);
}
else {
// Slope is positive
x1 = min(in_min, in_max);
x2 = max(in_min, in_max) + 1;
y1 = min(out_min, out_max);
y2 = max(out_min, out_max) + 1;
}
long dx = x2 - x1;
long dy = y2 - y1;
return ifloor((x - x1) * dy + y1 * dx, dx);
}