Reputation: 11
How do I fix the issue of duplication in the following code? The first entry is the same as the second for example.
Input:
import numpy as np
t_max=np.arange(0,2.1,0.1)
for j in range (2,len(t_max)):
time=np.arange(t_max[2],t_max[j]+0.1,0.1)
print(time)
Output:
[0.2 0.3]
[0.2 0.3]
[0.2 0.3 0.4]
[0.2 0.3 0.4 0.5]
[0.2 0.3 0.4 0.5 0.6]
[0.2 0.3 0.4 0.5 0.6 0.7 0.8]
[0.2 0.3 0.4 0.5 0.6 0.7 0.8]
[0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9]
[0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1. ]
[0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1. 1.1 1.2]
[0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1. 1.1 1.2 1.3]
[0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1. 1.1 1.2 1.3 1.4]
[0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1. 1.1 1.2 1.3 1.4 1.5]
[0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1. 1.1 1.2 1.3 1.4 1.5]
[0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1. 1.1 1.2 1.3 1.4 1.5 1.6 1.7]
[0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1. 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8]
[0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1. 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8]
[0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1. 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9]
[0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1. 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9
2. ]
Upvotes: 1
Views: 56
Reputation: 388
This question is about why 0.1+0.2>0.3
in computer programming language.
In your case, when j=2
the code is turn to np.arrange(0.2, 0.2+0.1, 0.1)
.
There's code output below:
Input:
a = np.arange(0.2,0.3,0.1)
print(a)
Output:
[0.2]
Input:
a = np.arange(0.2,0.2+0.1,0.1)
print(a)
[0.2 0.3]
You can just simply use round
to fix it in your case. Like this:
time=np.arange(t_max[2],round(t_max[j]+0.1,1),0.1)
Output:
[0.2]
[0.2 0.3]
[0.2 0.3 0.4]
[0.2 0.3 0.4 0.5]
[0.2 0.3 0.4 0.5 0.6]
[0.2 0.3 0.4 0.5 0.6 0.7 0.8]
[0.2 0.3 0.4 0.5 0.6 0.7 0.8]
[0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9]
[0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1. ]
[0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1. 1.1]
[0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1. 1.1 1.2]
[0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1. 1.1 1.2 1.3]
[0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1. 1.1 1.2 1.3 1.4]
[0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1. 1.1 1.2 1.3 1.4 1.5]
[0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1. 1.1 1.2 1.3 1.4 1.5 1.6]
[0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1. 1.1 1.2 1.3 1.4 1.5 1.6 1.7]
[0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1. 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8]
[0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1. 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9]
[0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1. 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 2.]
Upvotes: 0
Reputation: 71560
Just try using slicing:
import numpy as np
t_max=np.arange(0,2.1,0.1)
for j in range(4, len(t_max) + 1):
time=t_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