Question about the Range of randint Function in GlowScript

35 views
Skip to first unread message

송석리 (석리송)

unread,
Nov 25, 2024, 12:35:26 AM11/25/24
to VPython-users

Hello,

I am an educator who has been using GlowScript to conduct various educational programs with high school students and teachers.

I've been using GlowScript for eight years, and while I've continued teaching with the hope that this issue might be fixed someday, I am now writing a related textbook and wanted to ask about this matter.

In standard Python, when using the randint function, randint(a, b) generates an integer n such that a ≤ n ≤ b.

However, in GlowScript, it seems that randint(a, b) generates an n such that a < n ≤ b, which is significantly inconsistent with Python's usage. I'm curious if there is any rational reason for using this range.

(I thought perhaps it's because GlowScript uses JavaScript functions, but even in JavaScript, there doesn't seem to be such an unusual range as a < n ≤ b.)

Thank you in advance for your assistance.

Bruce Sherwood

unread,
Nov 25, 2024, 1:32:06 PM11/25/24
to VPython-users
I am unable to reproduce this bug, as the following program displays plenty of zeros:

Web VPython 3.2
from random import randint
print_options(height=500)
r = 0
while r < 20:
    print(randint(0,5))
    r += 1

송석리

unread,
Nov 26, 2024, 12:24:01 AM11/26/24
to vpytho...@googlegroups.com

I apologize for the confusion earlier. Upon further investigation, I found that the randint() function in the GlowScript environment works correctly within positive ranges. However, the issue arises when negative numbers are included in the range. For example, the following code should logically result in the box either moving to the left, staying in place, or moving to the right. However, when I run it, the box only moves to the right. Could you provide any insights or solutions regarding this behavior?


import random b = box() while True: rate(10) b.pos.x = b.pos.x + random.randint(-1,1)

Thank you for your time and assistance.

Bruce Sherwood

unread,
Nov 26, 2024, 2:14:37 PM11/26/24
to VPython-users
Okay, I see that if the first number is -5, -5 is never generated. I've reported the bug to the developer of RapydScript-NG. Interesting that in 10 years of Web VPython no one reported this until now.

I can think of a workaround:

from random import randint
def rint(a,b):
    if a < 0:
        return randint(a-1,b)
    else:
        return randint(a,b)
i = 0
while i < 20:
    print(rint(-2,2))
    i += 1

Bruce
Reply all
Reply to author
Forward
0 new messages