python - 从边界内行进的距离获取位置 X

标签 python

我有两个向相反方向移动的蓝点。我给出了点可以移动的 X 轴的大小限制。在此示例中,总共有 300 个单位(从 0 开始的任一方向均为 150 个)

每个蓝色点都从 0(中心)开始,我得到了每个点移动的总距离。我在编写一个返回结果 X 位置的函数时遇到了问题。在下图中用浅蓝色点表示。红线表示球可以在其中移动的边界,将红线视为墙壁,将蓝点视为弹跳球。

我的目标是创建一个在 python 中返回这个值的函数。

enter image description here

您会在我的函数中看到我有一个参数 dir,它用于确定球移动的方向(最初是向左还是向右)

以下是我尝试解决的问题,但并不完全正确。当 % 有余数时,它似乎失败了。

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

最佳答案

% 和绝对值:

代码:

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

测试代码:

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

关于python - 从边界内行进的距离获取位置 X,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43970127/

相关文章:

python - Google Sheet API 中的 Spreadsheets.values.batchUpdate() 中的每个范围更新都是请求调用

python - 如何从命令行初始化要在多次调用 Python 中使用的对象

python - networkx 中更大图的完全连接子图

python - 第一个 Python Tkinter 窗口可以工作,但其余窗口是空白的

python - Django 无法处理非 ascii 符号

python - 我用 Python 编写的广义 Student-T 概率分布没有积分为 1(在某些情况下)

python - 从忽略 inf 和 nan 的 numpy 数组中获取最小的 N 个值

Python win32crypt.CryptProtectData 2.5 和 3.1 之间的区别?

python - 如何在Python中重置字典中的值?

python - 如何考虑同一 DAG 中先前任务的结果来创建动态数量的任务?