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?

5
  • One possible solution is pass a number as an argument: def number(num): and then in the loop: b=b+num Commented Aug 13, 2021 at 2:22
  • If you don't mind 1.0 instead of 1 as an output, you could use round(c, 1). Commented Aug 13, 2021 at 2:23
  • for i in range(10): c=next(b)*2 print(c)#something like this? Commented Aug 13, 2021 at 2: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. Commented Aug 13, 2021 at 3: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. Commented Aug 13, 2021 at 10:35

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

1 Comment

Could you again check my post? I have made some changes.
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

Comments

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

1 Comment

Could you again check my post. If it is possible.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.