如何在Swift中从无限数中得出一个值? [英] How to derive a value from a infinite number in Swift?

查看:232
本文介绍了如何在Swift中从无限数中得出一个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我下面的函数偶尔会产生一个无限数.我以为我可以在下面使用舍入函数来避免使用无穷大...换句话说,将1.333333333333(INF)舍入为1.33,但是编译器仍将INF.rounded的结果视为无穷大,我如何舍入这样我仍然可以在此处输入值?具体地说,我正在尝试编码为JSON并收到此错误:

My function below will occasionally produce an infinite number. I had thought that I could use my rounding function below to avoid using the infinite number...in other words 1.333333333333(INF) rounded to 1.33, however the compiler still treats the result of the INF.rounded as infinite, how can I round so that I can still put out a value here? Speficially I'm trying to encode to JSON and getting this error:

metadata ERROR = invalidValue(inf, Swift.EncodingError.Context(codingPath: [Watch_Extension.HockeyTrackerMetadata.(CodingKeys in _B2A7010AF20490DAF638D1E0A01E4982).maximumCapableSpeed], debugDescription: "Unable to encode Double.infinity directly in JSON. Use JSONEncoder.NonConformingFloatEncodingStrategy.convertToString to specify how the value should be encoded.", underlyingError: nil))

//Calculation  
 func calculateMaximumAndAverageSkatingEfficiency() {

        let heartRateUnit:HKUnit = HKUnit(from: "count/min")
        let heartRatesAsDouble = heartRateValues.map { $0.quantity.doubleValue(for: heartRateUnit)}
        let maxHeartRate = heartRatesAsDouble.max()
        guard let maxHeartRateUnwrapped = maxHeartRate else { return }

        maximumEfficiencyFactor = ((1760.0 * (maxSpeed / 60)) / maxHeartRateUnwrapped).round(to: 2)

        guard let averageIceTimeHeartRateUnwrapped = averageIceTimeHeartRate else { return }

        averageEfficiencyFactor = ((1760.0 * (averageSpeed / 60)) / averageIceTimeHeartRateUnwrapped).round(to: 2)

    }

//Round extension I am using
extension Double {

    func round(to places: Int) -> Double {
        let divisor = pow(10.0, Double(places))
        return Darwin.round(self * divisor) / divisor
    }

}

//Usage 
  if let averageEfficiencyFactorUnwrapped = averageEfficiencyFactor {
            metadata.averageEfficiencyFactor = averageEfficiencyFactorUnwrapped.round(to: 2)
        }

推荐答案

无穷大"表示该值是正无穷大或负无穷大,可能是因为它是被零除或类似的数学运算的结果.这并不意味着该值是一个非终止的十进制数.

"Infinite value" means that the value is positive or negative infinity, probably because it was the result of a division by zero or a similar mathematical operation. It does not mean that the value is a non-terminating decimal.

确保maxHeartRateUnwrappedaverageIceTimeHeartRateUnwrapped不为零.

这篇关于如何在Swift中从无限数中得出一个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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