[swift-evolution] [Discussion] stride behavior and a little bit of a call-back to digital numbers

Joe Groff jgroff at apple.com
Sat Feb 27 18:46:25 CST 2016


> On Feb 27, 2016, at 3:27 PM, Erica Sadun <erica at ericasadun.com> wrote:
> 
> Under the current implementation, each floating point addition accrues errors. The progression never reaches 2.0. 
> 
> print(Array(1.0.stride(through: 2.0, by: 0.1)))
> /// Prints [1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9]
> To force the progression to include 2.0, you must add an (ugly) epsilon, as in the following example:
> 
> print(Array(1.0.stride(through: 2.01, by: 0.1)))
> /// Prints [1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0]
> This is problematic for the following reasons: 
> 
> The name of the calling function “through” suggests the progression will pass through the end point before stopping
> Floating point calls present an extremely common use-case
> It’s unreasonable to expect developers to consider every case of “will floating point math prevent my progression from actually reaching the end point, which has already been differentiated by using through rather than to”
As implemented, `stride` is broken for floating-point numbers. Instead of repeatedly adding the `by` interval, it should multiply the interval by successive integral values and add that to the base to avoid accruing error. Your proposal only papers over the problem.

-Joe
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160227/7e3551fd/attachment.html>


More information about the swift-evolution mailing list