我一直试图编写一个函数,它接受变量a和b作为起点和终点,并计算从a到b的距离为0到1之间的分数。(该分数是变量x )。
我已经部分工作的代码,但它并不总是与负数一起正常工作。例如,如果a = -2
和b = -1
以及x = 1
输出应为-1,但我得-2。
到目前为止,我一直使用if
语句解决类似的问题,但我不想继续这样做。有更优雅的解决方案吗?
def interval_point(a, b, x):
"""Given parameters a, b and x. Takes three numbers and interprets a and b
as the start and end point of an interval, and x as a fraction
between 0 and 1 that returns how far to go towards b, starting at a"""
if a == b:
value = a
elif a < 0 and b < 0 and x == 0:
value = a
elif a < 0 and b < 0:
a1 = abs(a)
b1 = abs(b)
value = -((a1-b1) + ((a1-b1)*x))
else:
value = (a + (b-a)*x)
return(value)
答案 0 :(得分:0)
我在数学上玩了一些,我已经找到了解决问题的简单方法。
这就是现在的功能:
def interval_point(a, b, x):
"""Given parameters a, b and x. Takes three numbers and interprets a and b
as the start and end point of an interval, and x as a fraction
between 0 and 1 that returns how far to go towards b, starting at a"""
return((b - a) * x + a)