下面2個代數等價公式並聯電阻:計算並聯連接電阻
par1(r1, r2) = (r1 * r2)/(r1 + r2), or
par2(r1, r2) = 1/(1/r1 + 1/r2)
繼兩個Python函數,其中的每一個計算parallel_resistors式:
def par1(r1, r2):
return div_interval(mul_interval(r1, r2), add_interval(r1, r2))
def par2(r1, r2):
one = interval(1, 1)
rep_r1 = div_interval(one, r1)
rep_r2 = div_interval(one, r2)
return div_interval(one, add_interval(rep_r1, rep_r2))
下面是一個區間運算抽象由前述功能par1
和par2
使用。
def interval(a, b):
"""Construct an interval from a to b. """
return (a, b)
def lower_bound(x):
"""Return the lower bound of interval x. """
return x[0]
def upper_bound(x):
"""Return the upper bound of interval x. """
return x[1]
def div_interval(x, y):
"""Return the interval that contains the quotient of any value in x divided
by any value in y.
Division is implemented as the multiplication of x by the reciprocal of y.
>>> str_interval(div_interval(interval(-1, 2), interval(4, 8)))
'-0.25 to 0.5'
"""
assert (lower_bound(y) > 0 or upper_bound(y) < 0), "what it means to divide by an interval that spans zero"
reciprocal_y = interval(1/upper_bound(y), 1/lower_bound(y))
return mul_interval(x, reciprocal_y)
def str_interval(x):
"""Return a string representation of interval x.
>>> str_interval(interval(-1, 2))
'-1 to 2'
"""
return '{0} to {1}'.format(lower_bound(x), upper_bound(x))
def add_interval(x, y):
"""Return an interval that contains the sum of any value in interval x and
any value in interval y.
>>> str_interval(add_interval(interval(-1, 2), interval(4, 8)))
'3 to 10'
"""
lower = lower_bound(x) + lower_bound(y)
upper = upper_bound(x) + upper_bound(y)
return interval(lower, upper)
def mul_interval(x, y):
"""Return the interval that contains the product of any value in x and any
value in y.
>>> str_interval(mul_interval(interval(-1, 2), interval(4, 8)))
'-8 to 16'
"""
p1 = lower_bound(x) * lower_bound(y)
p2 = lower_bound(x) * upper_bound(y)
p3 = upper_bound(x) * lower_bound(y)
p4 = upper_bound(x) * upper_bound(y)
return interval(min(p1, p2, p3, p4), max(p1, p2, p3, p4))
測試結果:
>>> r1 = interval(1, 2)
>>> r2 = interval(3, 4)
>>> par1(r1, r2)
(0.5, 2.0)
>>> par2(r1, r2)
(0.75, 1.3333333333333333)
我們注意到從par1
和par2
了不同的結果,它通過計算不同,但代數等價表達式。 對於上面給出的輸入r1和r2,以下是計算。
par1 --> return mul_interval((3, 8), (1/6, 1/4)) = (1/2, 2)
=======
rep_r1 = div_interval((1, 1), (1, 2)) = (1/2, 1)
rep_r2 = div_interval((1, 1), (3, 4)) = (1/4, 1/3)
par2 --> return div_interval((1, 1), (3/4, 4/3)) = (3/4, 4/3)
其原因不同間隔是由於IEEE浮點格式,其中每div_interval
失去精度。
我的理解是否正確?
的上界應該是'X [-1]'我猜? – ZdaR
@anmol_uppal請測試並找到您的問題的答案。 – overexchange
請給出downvote的原因,以進一步完善這個問題 – overexchange