How to find max value for Double and Float in Swift

后端 未结 7 1622
情歌与酒
情歌与酒 2020-12-23 23:55

Current learning Swift, there are ways to find max and min value for different kind of Integer like Int.max and Int.min

相关标签:
7条回答
  • 2020-12-24 00:53

    While there’s no Double.max, it is defined in the C float.h header, which you can access in Swift via import Darwin.

    import Darwin
    
    let fmax = FLT_MAX
    let dmax = DBL_MAX
    

    These are roughly 3.4 * 10^38 and 1.79 * 10^308 respectively.

    But bear in mind it’s not so simple with floating point numbers (it’s never simple with floating point numbers). When holding numbers this large, you lose precision in a similar way to losing precision with very small numbers, so:

    let d = DBL_MAX
    let e = d - 1.0
    let diff = d - e
    diff == 0.0  // true
    
    let maxPlusOne = DBL_MAX + 1
    maxPlusOne == d  // true
    
    let inf = DBL_MAX * 2
    // perhaps infinity is the “maximum” 
    inf == Double.infinity  // true
    

    So before you get into some calculations that might possibly brush up against these limits, you should probably read up on floating point. Here and here are probably a good start.

    0 讨论(0)
提交回复
热议问题