FORUM CTRLX AUTOMATION
ctrlX World Partner Apps for ctrlX AUTOMATION
06-13-2023 12:41 PM
Is there a way to improve conversion accuracy when doing REAL_TO_LREAL conversions?
Example:
lrTemp:=REAL_TO_LREAL(rTemp);
real variable, rTemp = 84.38, the long real lrTemp= 84.379997253417969.
Is there a way to make lrTemp also = 84.38?
Many thanks
Solved! Go to Solution.
06-13-2023 01:23 PM
LREAL has double the precision versus REAL:
https://en.wikipedia.org/wiki/Double-precision_floating-point_format
Its just codesys that shows it abit strange in certain cases, but with alot of shown decimals you see that most of the decimals are the same in both cases:
Use %.2f in displays to show it with only two decimal points:
06-13-2023 03:19 PM
Thanks @AndreasL .
If I do a LREAL_TO_REAL conversion then I get values as in your example as expected but problem is REAL_TO_LREAL.
The reason it is an issue is because I was writing to drive limit in motion app (Lreal data type) from a value on HMI (real data type). When I set some values (e.g. 84.38 as real) this showed incorrectly in motion app (e.g. 84.379997253417969 within CtrlX web browser) so just think it is a little confusing.
I assume we would have same problem with target postions also where a conversion is done from real to lreal to suit the PLC Open function block inputs.
I guess I just have to change all the existing recipe and setup variables from real to lreal to ensure no confusion
Thanks anyway
06-13-2023 09:21 PM
It's actually not a incorrect value, 84.38 is not representable by IEEE754 floating point numbers:
https://www.binaryconvert.com/result_double.html?decimal=056052046051056
https://www.binaryconvert.com/result_float.html?decimal=056052046051056
But it's really really close in both 32bit and 64bit floats.
This is the reason floats are never used when dealing with currencies, floats are good for alot of stuff, but there is always a limited accuracy of them.
06-16-2023 08:57 AM
Thanks for the explanation. In the end I decided for 2 decimal place accuracy and did following conversion in code to ensure value displayed same in Motion App:
HMI Real setpoint * 100...REAL_TO_DINT...DINT_TO_LREAL...LREAL/100.