15 digit floating variable calculation in microcontroller

54 Views Asked by At

I want to calculate an equation within a controller(Arduino)

y = -0.0000000104529251928664x^3 + 0.0000928316793270531x^2 - 0.282333029643959x + 297.661280719026

Now the decimal values of the coefficients are important because "x" varies in thousands so cube term cannot be ignored. I have tried manipulating the equation in excel to reduce the coefficients but R^2 is lost in the process and I would like to avoid that.

enter image description here

Max variable size available in Arduino is 4byte. And on google search, I was not able to find an appropriate solution.

Thank you for your time.

2

There are 2 best solutions below

4
On

As far as I understand the Arduino specifications, the number $-0.0000000104529251928664$ will be rounded to approximately $-0.00000001045293.$ In scientific notation, that's $$ 1.045293 \times 10^{-8}. $$

You'll lose some precision because only four-byte floating-point numbers are supported, but you won't lose the $x^3$ term completely. In fact it will be very nearly as accurate (relative to its mathematically correct value) as any of the other terms.

On the other hand, what happens to $R^2$ if you divide the $x$ coordinate of every data point by $2000$ and use the equation \begin{multline} y = -83.6234015429312 x^3 + 371.3267173082124 x^2 \\ - 564.666059287918 x + 297.661280719026? \end{multline}

0
On

You can improve the accuracy by defining $u=x-2500$ and rewriting your polynomial in terms of $u$. It doesn't help much in this case, but the maximum value of $u^3$ is about $10^9$ where $x^3$ goes up to about $43 \cdot 10^9$. Your equation does not seem to have any spectacular cancellation, so computing in single precision should be fine. The fact that the cubic term starts with a bunch of zeros will be taken care of by the floating point. You will have about seven decimal digits of numerical accuracy, which is more than is justified by the fit you have.