[swift-evolution] floating point numbers implicit conversion

John McCall rjmccall at apple.com
Mon Jun 19 17:08:24 CDT 2017


> On Jun 19, 2017, at 5:43 PM, David Sweeris <davesweeris at mac.com> wrote:
> Sent from my iPhone
> On Jun 19, 2017, at 13:44, John McCall via swift-evolution <swift-evolution at swift.org <mailto:swift-evolution at swift.org>> wrote:
> 
>>> On Jun 19, 2017, at 1:58 PM, Stephen Canon via swift-evolution <swift-evolution at swift.org <mailto:swift-evolution at swift.org>> wrote:
>>>> On Jun 19, 2017, at 11:46 AM, Ted F.A. van Gaalen via swift-evolution <swift-evolution at swift.org <mailto:swift-evolution at swift.org>> wrote:
>>>> 
>>>> var result: Float = 0.0
>>>> result = float * integer * uint8 +  double   
>>>> // here, all operands should be implicitly promoted to Double before the complete expression evaluation.
>>> 
>>> You would have this produce different results than:
>>> 
>>> 	let temp = float * integer * uint8
>>> 	result = temp + double
>>> 
>>> That would be extremely surprising to many unsuspecting users.
>>> 
>>> Don’t get me wrong; I *really want* implicit promotions (I proposed one scheme for them  way back when Swift was first unveiled publicly).
>> 
>> I don't!  At least not for floating point.  It is important for both reliable behavior and performance that programmers understand and minimize the conversions they do between different floating-point types.
> 
> How expensive is it?

If memory serves, it's not usually ruinously expensive on its own, but there tend to not be very many functional units for it, and it doesn't get pipelined very well.  Essentially, micro-architects often assume that well-written FP code is not doing a significant number of FP conversions.  Even if it were very cheap, it would still be an unnecessary operation in the pipeline.

It's a well-known source of performance bugs in C to accidentally use 1.0 instead of 1.0f in the middle of some complex expression that's heavily working with floats.  A bunch of intermediate computations ends up getting done in double, and unlike the analogous situation with integers, it's not really possible for the compiler to automatically figure out that it can do them in float instead.

John.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170619/4348c98e/attachment.html>


More information about the swift-evolution mailing list