如何在Swift中找到Double和Float的最大值 [英] How to find max value for Double and Float in Swift

查看:2723
本文介绍了如何在Swift中找到Double和Float的最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前正在学习Swift,有一些方法可以找到不同类型的整数 max 值,如 Int .max Int.min



有没有办法找到Double和Float的最大值?此外,我应该提及哪个文件提出这样的问题?我正在阅读Apple的 Swift编程语言

解决方案

虽然没有 Double.max ,它定义在C float.h 标题中,您可以通过导入在Swift中访问达尔文

  import达尔文

let fmax = FLT_MAX
let dmax = DBL_MAX

这些大概是 3.4 * 10 ^ 38 1.79 * 10 ^ 308



但是请记住,它不是那么简单浮点数(浮点数并不简单)。当你拿着这个数字很大的时候,你会以类似的方式失去精确度,以非常小的数字丢失精度,所以:

  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
//也许无穷大是最大
inf == Double.infinity // true $ b $因此,在进行一些可能会刷新这些限制的计算之前,您应该可以读取浮点数。 此处 here 可能是一个好的开始。


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

Is there a way to find max value for Double and Float? Moreover, which document should I refer for this kind of question? I am currently reading Apple's The Swift Programming Language.

解决方案

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.

这篇关于如何在Swift中找到Double和Float的最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆