Code style query: multiple assignments in if/elif tree
Steven D'Aprano
steve at pearwood.info
Tue Apr 1 03:20:37 EDT 2014
On Tue, 01 Apr 2014 16:01:40 +1100, Chris Angelico wrote:
[...]
>> The scenario you describe has (effectively) infinite rate-of-change-of-
>> acceleration, often called "jerk". (A jerk is a rapid change in
>> acceleration.) Human comfort is (within reasonable limits) more
>> affected by jerk than acceleration. The passengers will feel three
>> quite distinctive jerks, one when the brakes are first applied (which
>> is probably reasonable), then one at 1s, then again at 2s. That's not
>> comfortable by any stretch of the imagination.
>
> It actually is a smooth increase in deceleration, but I'm operating the
> simulator on a 1s period, so it's actually an average across the first
> second, and an average across the next second...
Hmmm. A 1-second resolution doesn't really sound too great to me.
Suppose the deceleration increases linearly from 0 to 0.85 m/s over two
seconds. Averaging it in the way you suggested, we get a total distance
of:
2*u - 0.5125
(see my previous post for details) where u is measured in metres per
second. Multiply by seconds to get the units right. For a Japanese bullet
train where u = 320 km/hr that corresponds to
py> 2*88.888889 - 0.5125
177.26527800000002
metres.
Now let's do it properly! Given our assumption that the deceleration is
linear, the jerk will be constant:
j = Δa/Δt
= (0.85 - 0)/2
= 0.425 m/s^3
Let's start integrating!
py> from sympy import integrate
py> from sympy.abc import t
py> j = '0.425'
py> a = integrate(j, t)
py> v = 88.888889 - integrate(a, t)
py> s = integrate(v, (t, 0, 2))
py> s
177.211111333333
compared to 177.26527800000002 calculated the rough way. That's not bad,
only about 5cm off! Effectively, your rough calculation was accurate to
one decimal place.
Of course, if the equation for acceleration was more complex, the
approximation may not be anywhere near as good.
[...]
>> This becomes a simple question for the four standard equations of
>> motion:
>>
>> (1) v = u + at
>> (2) s = 1/2(u + v)t
>> (3) s = ut + 1/2(at^2)
>> (4) v^2 = u^2 + 2as
>>
>> Only (1) and (3) are needed.
>
> Okay, what's u here? Heh.
They're *standard* equations of motion. Weren't you paying attention
through the, oh, three years of high school where they teach this? :-P
s = displacement (distance)
t = time
u = initial velocity
v = final velocity
a = acceleration
[...]
> Fair enough. :) That's why I asked. Is it naughty enough to break into
> two statements, or is it better to combine it into a single multiple
> assignment?
Since they are unrelated assignments, of two different variables, they
should be written as two separate assignments, not one using sequence
unpacking.
--
Steven
More information about the Python-list
mailing list