1

It can be strange when I tried to run a program and I found something unexplainable.

import numpy as np

j = 0
start = 0.2
end = 0.8
step = 0.01

for i in np.arange(start, end, step):

    print('i is ', i)
    print('i is bigger than end is', i > end)
    print('j is ', j)
    print(' ')
    j+=1

The outcome shows that the last i is bigger than the upper bound???

part outcome

I tried many other combinations of start and end, but they all seemed to be normal. So why does this happen when the lower bound is 0.2 and the upper bound is 0.8? Is there anything about np.arange that I don't know? Or maybe the fractional part somehow affect the outcome? (btw, I know that there are plenty of ways to fix this, just be curious)

wanger
  • 11
  • 2
  • You need to post the code that generated the output. We cannot give an answer without it. – Inyoung Kim 김인영 Dec 03 '22 at 09:24
  • Although it seems due to floating point error of the last digit being 5. Floating point numbers (numbers with decimals) tend to have unnoticeable errors. In your case, the last digit being 5 is the error. – Inyoung Kim 김인영 Dec 03 '22 at 09:25
  • Sorry, new comer... Can't embed the picture yet, there are links before and I add the embedded codes. I know there is a floating point error when I do this, but the tricky part is that if you change the start or the end number, the last i will not go beyond the upper bound. – wanger Dec 03 '22 at 09:39
  • Instead of posting it as picture, you could copy and paste the terminal as code also :D – Inyoung Kim 김인영 Dec 03 '22 at 09:42
  • Right, I tried before, but the outcome of the XShell terminal seems not to support the copy operation like Ctrl+C or Ctrl+insert. (but I got 10 points of reputation now -.-) – wanger Dec 03 '22 at 09:46
  • I just ponder through the questions, and I think there is actually a difference between the two questions. In my case, the last `i` is greater than the end number 0.8(according to the outcome), but it still goes into the loop, and why is that? In the other case, 8.4 that `i` represents is actually smaller than 8.4 that the end point represents due to the float point error, so it can go into the loop. – wanger Dec 03 '22 at 10:18
  • `np.arange(.2,.8,.01)` creates an array of 61 values. If you print that directly, you'll see values rounded to 2 decimals. print `list(np.arange ....))` shows them individually with the "extra" 2/4/5 way at the end. Your `for` iteration is over that list. `arange` warns about "inconsistent" results when using a float step. Python `for` is over a list or `generator` (like `range`). You aren't specifying the upper bounds of the iteration. – hpaulj Dec 03 '22 at 17:14

0 Answers0