Reputation: 3
def number():
b = 0.1
while True:
yield b
b = b + 0.1
b = number()
for i in range(10):
print(next(b))
Outputs
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
0.9999999999999999
Then, I just want
c=b*2
print("c="=)
My expected outputs are
c=0.2
0.4
0.6
0.8
1
1.2
And so on.
Could you tell me what I have to do to get my expected outputs?
Upvotes: 0
Views: 92
Reputation:
Like this?
for i in range(10):
AnotherB=next(b)
c=AnotherB*2
print(AnotherB)
print("c="+str(c))
or do you mean how do you reset a yeild? just redeclare it.
def number():
b = 0.1
while True:
yield round(b,1)
b = b + 0.1
b = number()
for i in range(10):
print(next(b))
b=number()
for i in range(10):
print("c="+str(next(b)*2))
Upvotes: 0
Reputation:
You can pass the number as an argument:
def number(start=0.1,num=0.1):
b = start
while True:
yield round(b,1)
b += num
b = number(0,0.2)
It yields:
0
0.2
0.4
0.6
0.8
1.0
1.2
1.4
1.6
1.8
Upvotes: 0
Reputation: 198566
Floating point numbers are not precise. The more you handle them, the more error they can accumulate. To have numbers you want, the best way is to keep things integral for as long as possible:
def number():
b = 1
while True:
yield b / 10.0
b += 1
Upvotes: 2