NoRt9001 NoRt9001 - 1 year ago 95
Python Question

How to take reciprocal of a float in python

I'm having some trouble in my pygame application that I'm making. There are buttons in the menu that change how fast my simulation runs (by changing

). This, however, also slows down the rate that the menu buttons respond. If I ingame set
anywhere lower than 0.5 the speed and play/pause buttons take up to five seconds to register a click. So I tried creating my own way to work around this:

speed = 1 # defined previously ingame

timeSlow = 0
timeSlowGoal = 0

while True: # game loop

if speed < 1:

timeSlowGoal = reciprocal(speed) # well here's my problem

timeSlowGoal = -1

if timeSlowGoal != -1:

if timeSlow >= timeSlowGoal:
timeSlow = 0
# more code that actually does stuff

timeSlow += 1
# doesn't match, try again

In python, there are tricks like
, and
to change a variable. Of course,
doesn't work. Is there some sort of function like these that gets the reciprocal of a number, (which in this case is always a decimal) or do I need to just do some fancy math to get it?

(of course if all of this is unnecessary and you have a better solution to my first problem let me know)

EDIT: Okay, there is a very simple solution to this that I overlooked. 1/n is always the reciprocal of n. There's no need for a reciprocal() function because it's so simple. That's what I get for forgetting elementary school math.

Answer Source

Assuming you are using Python 3, change

timeSlowGoal = reciprocal(speed)


timeSlowGoal = 1 / speed

Just make sure that you don't try to do that if speed is zero.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download