[swift-evolution] implementing real (floating point) number comparison tolerance as a compiler directive.
Ted F.A. van Gaalen
tedvgiosdev at gmail.com
Fri Mar 4 07:11:38 CST 2016
Hi Joe,
to just fuzzy compare 2 floating point numbers,
the solution you describe uses
- 2 functions, with therein 6 calls to frexp, abs, max and scalb...
isn’t that overkill ?
I still think a compiler directive embedded in sources at desired locations as e.g.
@setFLoatingPointTolerance: 0.0001
.
if a == b
...
@setFloatingPointToleranceOff
…
@setFLoatingPointTolerance: 0.04
.
if temperature == roomTemperature
...
@setFloatingPointToleranceOff
So every floating point compare in source between these directives will be
will be compiled differently.
Leave it to the compiler, so no special functions/ parameters are needed,
and would be far more efficient I think.
Kind Regards
TedvG
> On 02.03.2016, at 22:28, Joe Groff <jgroff at apple.com> wrote:
>
>>
>> On Mar 2, 2016, at 1:23 PM, Tino Heth via swift-evolution <swift-evolution at swift.org <mailto:swift-evolution at swift.org>> wrote:
>>
>> I hope that I'll finally have the time to write a pitch for "inheritance for structs" this weekend — this looks like another good use case for a "newtype" feature:
>>
>> struct Length: Double {
>> static let tolerance: Double = 0.001
>> }
>>
>> override func ==(a: Length, b: Length) -> Bool {
>> return (a - b).abs() < Length.tolerance
>> }
>>
>> Of course, this example leaves many questions, but I hope the principle is clear.
>
> This is also a place where function partial application might be interesting:
>
> func equalityWithTolerance(tolerance: Double) -> (Double, Double) -> Bool {
> return {
> var exp0 = 0, exp1 = 0
> frexp($0, &exp0)
> frexp($1, &exp1)
> return abs($0 - $1) < scalb(tolerance, max(exp0, exp1))
> }
> }
>
> If you could locally bind operators, you could then do this:
>
> func compareLengths(x: Double, y: Double) -> Bool {
> let (==) = equalityWithTolerance(0x1p-44)
> return x == y // Uses local (==)
> }
>
> -Joe
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160304/bb66f130/attachment.html>
More information about the swift-evolution
mailing list