Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get position-X from distance traveled within boundaries

Tags:

python

I have two blue points moving in opposite directions. I'm given the size limit on the X-Axis in which the points can move. In this example it's 300 units total (150 in either direction from 0)

Each blue point starts at 0 (the center) and I'm given the total distance at which each point has moved. I'm having trouble writing a function which returns me their resulting X position. Which is indicated by a light blue dot in the image below. The red line indicates the boundaries which ball can move within, think of the red lines as walls and the blue points as bouncing balls.

My goal is to make a function which returns me this value in python.

enter image description here

You'll see in my function that I have an argument dir which is meant to be used to determine which direction the ball is moving (left or right initially)

Below is my attempt at solving it, but it's not entirely correct. It seems to fail when there are remainders from the %.

def find_position(dir=1, width=10, traveled=100):
    dist = traveled
    x = dist % (width*0.5)
    print x

find_position(dir=1, width=300, traveled=567)
find_position(dir=1, width=300, traveled=5)
find_position(dir=-1, width=300, traveled=5)
find_position(dir=-1, width=300, traveled=325)


>> output
117.0
5.0
5.0
25.0

>> should be
-33.0
5.0
-5.0
25.0
like image 835
JokerMartini Avatar asked Jan 18 '26 13:01

JokerMartini


1 Answers

With a % and an absolute value:

Code:

def find_position(direction=1, width=10, traveled=100):
    half_width = width / 2
    t = abs((traveled + half_width) % (2 * width) - width) - half_width
    return -t * direction

Test Code:

assert int(find_position(direction=1, width=300, traveled=567)) == -33.0
assert int(find_position(direction=1, width=300, traveled=5)) == 5
assert int(find_position(direction=-1, width=300, traveled=5)) == -5
assert int(find_position(direction=-1, width=300, traveled=325)) == 25
like image 157
Stephen Rauch Avatar answered Jan 21 '26 02:01

Stephen Rauch