A student wants a simulation to advance in steps of 0.1 s and stop at exactly 1.0 s, and writes:
t = 0.0 dt = 0.1 while t != 1.0: t = t + dt print(t)
The program uses standard double-precision floating point. What happens when it runs?
It prints 1.1, because the condition is checked before the final update.
It prints 1.0 after ten passes, because ten steps of 0.1 add up to 1.0.
The loop never stops on its own, because t passes 1.0 without ever equalling it exactly.
It prints 0.9, because rounding error ends the loop one pass early.
Unlock full course notes by signing up
Tracing a three-sample rolling mean
A pressure logger smooths readings by reporting the mean of each group of three consecutive samples. A rolling sum is a stored total updated by removing the departing sample and adding the arriving sample.
The following Python code processes readings in kPa. Indices start at zero, and range(3, len(readings)) produces 3, 4, and 5.
Complete the table with the values immediately after each iteration. Enter exact integers; the column headings supply the units.
Calibration search with early rejection and ties
An engineer calibrates a voltage sensor using the correction y^=a+bx\widehat{y}=a+bxy=a+bx, where aaa is an offset in volts and bbb is dimensionless. A grid search tests combinations drawn from specified lists of parameter values.
The measured voltages are 0, 1, and 2 V, with corresponding reference voltages 1, 3, and 6 V. The code scores each parameter pair using its largest absolute residual. It abandons a pair when that pair is already worse than the best completed result.
Here, float("inf") is larger than any finite error, and break exits only the innermost loop. Report the final selected offset a in V, selected scale b, stored best error in V, and number of residual calculations. Enter all four answers as exact integers.
Designing a refinement loop for trapezoidal integration
You need to approximate the integral of a smooth function f(x)f(x)f(x) over [a,b][a, b][a,b] by repeatedly refining the trapezoidal rule. Let tol be a positive threshold for agreement between successive estimates, not a guaranteed bound on the actual integration error. Assume n_max is an integer at least 4. Write Python code that:
defines trap(f, a, b, n), which returns the trapezoidal-rule estimate with nnn equal sub-intervals using an accumulation loop;
defines integrate(f, a, b, tol, n_max), which starts with n=4n = 4n=4, doubles nnn for each permitted refinement, returns the estimate as soon as two successive estimates differ by less than tol, never uses more than n_max sub-intervals, and reports clearly when it stops without satisfying the agreement test.