I'm working on an application where users can create their own equations using different math functions, like, sqrt, log, pow, exp, etc. and app calculates them with the provided values and displays the result. User also has the option to select the number of digits they want to round the result to. I'm using 'Double' data type and having precision issues with some of the equation results.
Below are some examples:
Example1:
let a = 0.2
let b = 0.1
let result = a + b
print(result)
Printed result: 0.30000000000000004
Expected result: 0.3
Example2:
let a = 9.495
let b = 0.2
let result = a + b
print(result)
Printed result: 9.694999999999999
Expected result: 9.695
Once they calculate the equation there is a requirement to match the result with the provided text. Which in the above cases fails. One of the solutions is to use the “Decimal” data type, but math functions like square root and log are not available for the Decimal data type.
Please let me know if there is any way to resolve these issues by continuing to use “Double”. Or please help in writing a custom implementation for all math functions for ‘Decimal’, or could you inform us if Apple has any plans to make the calculator Apis available for developers?
Thanks in Advance.
You've asked this question before: https://developer.apple.com/forums/thread/730747
Firstly, go and read something about floating point. The issues you are seeing are inherent to how floating point works. I bet there are some great explanations out there if you search, better than anyone could write here.
Using an exact decimal data type can solve some of your problems. Specifically it can fix 0.1 + 0.2 = 0.3 and your other example, because these are a consequence of the number base - 0.1 is a terminating exact value in decimal, but a recurring fraction in binary - 0.0001100110011001100....
But it can't help with functions like sqrt
and sin
because the results of those functions cannot be exactly represented in any number base. Mostly likely you will want to show approximations to those values by limiting the number of significant digits.