0

I want to implement a loop from -1 to 1 with step 0.1. It should take around 21 step to complete. Like this:

(do ((i -1 (+ i 0.1)))
    ((= i 1) i)
  (display i))

But then I'm starting this code my compiler goes wild. There are much more then 21 step as I mentioned.

I also tried this one:

(do ((i -1.0 (+ i 0.1)))
    ((= i 1.0) i)
  (display i))

And end up with this:

(do ((i -1
        (string->number (~r (+ i 0.1) #:precision 1))
        ))
    ((= i 1) i)
  (display i))

I just wanted to do something like this in C++:

for (double x=-1; x<=1; x+=0.1) {
cout<<x<<endl;
}

This C++ code makes 21 step.

  • As Barmar said, this happens because floating point operations suffer from loss of precision. Anyway, you can improve your first solution a bit by changing the condition to `(>= i 1.0)`, so the loop ends. – Óscar López May 21 '20 at 21:42
  • 3
    Note that your C++ example would be just as wrong if you translated it correctly. The reason you see a difference is because you use `=` in racket but `>=` in C++. – amalloy May 22 '20 at 01:52
  • 2
    The correct approach is to compute N from -10 to 10 (integer type) and interpolate the float with N / 10.0 – coredump May 22 '20 at 11:16

0 Answers0