0
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?

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
  • One possible solution is pass a number as an argument: ```def number(num):``` and then in the loop: ```b=b+num``` –  Aug 13 '21 at 02:22
  • If you don't mind ```1.0``` instead of ```1``` as an output, you could use ```round(c, 1)```. – Chaos_Is_Harmony Aug 13 '21 at 02:23
  • for i in range(10): c=next(b)*2 print(c)#something like this? –  Aug 13 '21 at 02:28
  • 1
    You have changed the question considerably, and I don't know what you are asking any more. In general, changing the content of a question in a manner that invalidates existing answers (as opposed to clarifying the question) should not be done; you should have asked a new question instead. – Amadan Aug 13 '21 at 03:55
  • @Amadan: I've rolled the question back to the original content (modulo minor edits made by others to improve spelling/formatting). As you say, the OP should ask a new question rather than invalidating existing answers by asking a new (and to my mind, less clear on the problem) question through edits. – ShadowRanger Aug 13 '21 at 10:35

3 Answers3

2

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
Amadan
  • 191,408
  • 23
  • 240
  • 301
0

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
0

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))