1
$\begingroup$

Not looking for a solution necessarily, but just trying to understand why this issue occurrs.

I have a 'Do' loop which iterates some algorithm over values of a parameter 'x' with range {x,0,1,0.1} and creates a list of lists, called "AllData", with results of the algorithm and Prepends the value of x to the results of each iteration. So AllData looks something like this: {{0., results},{0.1, results}, ..., {1.`, results}} where the first position gives the value of x.

But, 'AllData' has floating-point errors for some values of 'x' (not all). So - instead of of x=0.3, it has x=0.30000000000000004 instead of of x=0.6, it has x=0.60000000000000001 instead of of x=0.7, it has x=0.70000000000000001

This is fine, except, when I want to separate AllData using Select, only some of the errors are recognized as such. I run Do[SpecificData[y]=Select[AllData, #[[1]]==y &],{y,0,1,0.1}]

The code mostly works. All SpecificData[y] (including SpecificData[0.3] and SpecificData[0.6]) are created just fine. But SpecificData[0.7] fails to recognize the elements where the value of 'x' is 0.70000000000000001`. OR perhaps it uses slightly different value of 0.7. Either way, if I try to output SpecificData[0.7], it gives no output. BUT, if I output "SpecificData[0.3]" or "SpecificData[0.6]", it gives an output.

If I manually change 0.70000000000000001`to 0.7 in AllData, and try to use the Select loop, it still fails to create SpecificData[0.7], which to me suggests that even the second Do loop (where I create SpecificData) is using slightly different value of 0.7.

I'm trying to understand why 0.30000000000000004 and 0.60000000000000001 are recognized as 0.3 and 0.6, but 0.70000000000000001` is not recognized as 0.7. Also, why is the simple Do loop adding floating-point error in some numbers and not in others?

$\endgroup$
4
  • 3
    $\begingroup$ The moral lesson is that you should have done {x, 0, 1, 1/10} instead. See this older thread. $\endgroup$ Jun 10, 2022 at 15:57
  • 1
    $\begingroup$ True. That's what I am doing now. But I still am curious for why this happens. $\endgroup$
    – Ssdmitten
    Jun 10, 2022 at 16:02
  • 1
    $\begingroup$ It's because floating points are dyadic, whereas 0.1 is not. The floating point value of 0.1 is 0.10000000000000000555. Sometimes this will make Do accidentally fail to reach the end value. I often use something like {x, N[Subdivide[0, 1, 10]]} to prevent that $\endgroup$
    – Coolwater
    Jun 10, 2022 at 16:56
  • $\begingroup$ Ah! This made me do a dive into floating point calculation, and I see the problem. Thanks for the solutions and for prompting me to learn something new. $\endgroup$
    – Ssdmitten
    Jun 23, 2022 at 20:28

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.