anb
anb

Reputation: 285

Should I define all values as Double or mixed Double and Float when those values will be calculated frequently?

In my program, there are some decimal values that should be defined float respect to their range.

But, in several calculations (multiply), ranges might be larger than 10^38, so I need to convert them to Double before the calculation.

Say the values are

let a: Float // maximum: 10
let b: Float // maximum: 10^20
let c: Float // maximum: 10^30

and the calculations are like

func multiplyAB() -> Float {
  return a * b
}

func multiplyBC() -> Double {
  return Double(b) * Double(c)
}

let d = multiplyBC()

What bothers me is which one is better performance-wise? Convert from Float to Double during calculation or define a, b, c as Double?

In other words, is converting from Float to Double a handy job to CPU (like realloc memory, handle precision and sort of things) comparing to calculate all numbers in Double?

BTW, why Apple use Double as the underlying value for CGFloat? Maximum value for Float is 10^38, which is pretty large respect to iPhone screen sizes and pixels can't be float (10.111 and 10.11 make no difference, right?).
What's the reason behind that?

Upvotes: 0

Views: 105

Answers (1)

Roi Zakai
Roi Zakai

Reputation: 302

from THE SWIFT PROGRAMMING LANGUAGE

"NOTE

Double has a precision of at least 15 decimal digits, whereas the precision of Float can be as little as 6 decimal digits. The appropriate floating-point type to use depends on the nature and range of values you need to work with in your code. In situations where either type would be appropriate, Double is preferred."

Upvotes: 2

Related Questions