0

In the following code list value is after 0.2 interval. But when I print (h,i_sample) value in the inner most loop why h value is different from the one outside loop?How can I fix this error? If I create list with interval of 0.5 rather than 0.2 it picks correct values(same inside and outside the loops).

list =np.arange(1.0,5.0,0.2)
print(list)

for h in list:
    print("Loop: ", h)

    for i_sample in range(3):
        print(h,i_sample)
user10163680
  • 253
  • 2
  • 11
  • I cannot reproduce, the values are the same. What exactly are you seeing, and what did you expect to see? – juanpa.arrivillaga Sep 05 '18 at 04:37
  • @juanpa.arrivillaga, reproducible with 2.7... – Stephen Rauch Sep 05 '18 at 04:42
  • my list is [1.0,1.2,1.4,1.6,1.8,....4.8]. In first for loop when I print h value it is exactly same as in list but when I print h in the innermost loop instead of getting 1.6 I get 1.599999. Can you please give a simple explanation for this. – user10163680 Sep 05 '18 at 04:44
  • @user10163680, please read the duplicate. It goes into detail on this. – Stephen Rauch Sep 05 '18 at 04:44
  • @user10163680 the simplest explanation, floating point numbers are not exact representations, and when you print them, Python will try to show you "sensible" versions. Read the linked duplicate. If you *really* want to understand, read [this paper](https://www.itu.dk/~sestoft/bachelor/IEEE754_article.pdf) – juanpa.arrivillaga Sep 05 '18 at 04:45
  • 1
    That explanation is hard for me – user10163680 Sep 05 '18 at 04:51
  • The `print(list)` line displays the values rounded to a common precision. `print(list.tolist())` will display the values in the full, ugly floating point detail. There's no difference in values, just a difference in how they are displayed.. – hpaulj Sep 05 '18 at 04:55
  • @user10163680, I understand the difficulty. But it really is not simple. If it were, people smarter than us would have fixed this long ago. Best I can say is that you can either ignore it, or try really hard to study it enough to understand it . Wish there was a better answer. – Stephen Rauch Sep 05 '18 at 04:55
  • i got little bit idea that python is sensitive to the precision. I can do that by %.1f. But in this way I have to apply a for loop to get precision upto 1 decimal point. Can it be done without applying for loop – user10163680 Sep 05 '18 at 05:15
  • @user10163680 it's *not Python*, it's *binary floating point numbers* – juanpa.arrivillaga Sep 05 '18 at 05:18
  • Yes I can get precision by %.1f or %.3f – user10163680 Sep 05 '18 at 05:20
  • @user10163680 that is *string formatting*, that doesn't affect the `float` objects. – juanpa.arrivillaga Sep 05 '18 at 05:35
  • After formatting h value in this way I assign that h value to a variable but then I get error that np.float64 can not be interpreted as string. After string foramtting Does this value remain 1.59999 – user10163680 Sep 05 '18 at 05:43

0 Answers0