4
$\begingroup$

The code below does not work. Can anyone tell me why? Thanks!

 For[t = -1, t <= 1, t = t + 0.01, 
 For[z = -1, z <= 1, z = z + 0.01, If[t*z == 0, Print[t, ", ", z]]]]
$\endgroup$
0

1 Answer 1

4
$\begingroup$

It's the result of error accumulation of float number:

Nest[# + 0.01 &, -1, 100]
% == 0
(* 7.5287*10^-16 *)
(* False *)

There're many ways to fix this, for example, using arbitrary-precision number. In your case a Precision of 1. is enough:

0.01`1 // Precision
Nest[# + 0.01`1 &, -1, 100]
% == 0
(* 1. *)
(* 0.*10^-1 *)
(* True *)

Or simply use exact number:

Nest[# + 1/100 &, -1, 100]
% == 0
(* 0 *)
(* True *)
$\endgroup$
2
  • $\begingroup$ What if I have a function gives numerical values, for example, if I have something like f(0.01,0.02)=0.2312, and I want to check if f(a,b)==0, how should I do this? $\endgroup$
    – lol
    Jul 4, 2016 at 18:19
  • $\begingroup$ @lol This depends on the structure of the function $\endgroup$
    – xzczd
    Jul 5, 2016 at 2:25

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.