robtillaart:
simplifying math gives always more accurate results.
voltage = ((adcvalue/10)*(5000.0/4095));
==>
voltage = adcvalue * 0.1221001;
Not always.... In this case, it will, because the first expression is poorly written, as it will truncate the division result, losing significance for some values of adcvalue. It is better wrtiten as:
voltage = (adcvalue*5000.0/4095)/10.0) ;
The compiler will collapse this expression to the second form at compile time, leaving the source code as documentation of where the 0.1221001 came from, rather than leaving it as a "magic number".
Yes, it's extremely important to "show your working" because otherwise there's no way to know what 0.1221001 represents or how to change it to match a new system (like a 3.3v Arduino.) I would also usually include a comment to describe the units, eg milliseconds.
The complier does a surprising amount of pre-calculation for you. It can work out much more complex equations than this and just use the result, which makes your code both faster and smaller.
RayLivingston:
Not always.... In this case, it will, because the first expression is poorly written, as it will truncate the division result, losing significance for some values of adcvalue. It is better wrtiten as:
voltage = (adcvalue*5000.0/4095)/10.0) ;
The compiler will collapse this expression to the second form at compile time, leaving the source code as documentation of where the 0.1221001 came from, rather than leaving it as a "magic number".
Regards,
Ray L.
OK you have a point,
I could add the original formula as comments
get completely rid of the magic numbers, including familiar ones!