Wednesday, October 28, 2026
HomeiOS Developmentios - Precision difficulty when computing weight vary given BMI vary in...

ios – Precision difficulty when computing weight vary given BMI vary in Swift

[ad_1]

I’m making a BMI app. I’ve this code:

enum MathHelper {
  static func computeBMI(kg: Decimal, cm: Decimal) -> Decimal {
    return kg / cm / cm * 10_000
  }

  static func computeWeight(cm: Decimal, bmi: Decimal) -> Decimal {
    return bmi * cm * cm / 10_000
  }
  
  static func computeWeightRange(
    cm: Decimal,
    bmiRange: (from: Decimal, to: Decimal))
    -> (from: Decimal, to: Decimal)
  {
    let fromWeight = computeWeight(cm: cm, bmi: bmiRange.from)
    let toWeight = computeWeight(cm: cm, bmi: bmiRange.to)
    return (from: fromWeight, to: toWeight)
  }
}

Now I print the from/to pair, with 1 fraction size.

print(Decimal.FormatStyle.quantity.precision(.fractionLength(1)).format(from))
print(Decimal.FormatStyle.quantity.precision(.fractionLength(1)).format(to))

Once I run this code with top 180 cm, BMI vary from 18.5 to 24.9 (which is the BMI vary for wholesome weight), I obtained 59.9 – 80.7 weight vary.

However this isn’t appropriate. The burden vary needs to be 59.7-80.8. As a result of if I put in 59.7 and 80.8 into the computeBMI operate and print end in 1 fraction size, it is nonetheless inside vary 18.5-24.9.

Be happy to strive it out. This above code is already minimal reproducible code.

[ad_2]

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments