SWIFT/IOS Implementing some arithmetic on share prices, doing a subtraction to arrive at a daily loss/gain figure
PLEASE NOTE: These are not accounting calculations, they are all about measuring investment performance therefore absolute accuracy is not required, instead the priority is completing trillions of calculations in a short a time as possible (sub second) - hence the use of floating point arithmetic. The problem I have described below becomes important because a very small multiplication error can become significant at the scale I am performing the calculations.
When using the default Float type, I get inaccurate results (see playground code) below.
import UIKit
var str = "Hello, playground"
let y: Float = 129.08
let t: Float = 130.29
let subtracted = t - y // results in 1.209991 !!!!!! not accurate, should be something like 1.209998
let returnVal = subtracted / y // Results in 0.009373966 also inaccurate
If I implement the same arithmetic in a spreadsheet I get the expected results (or near as dammit): 130.29 - 129.08 = 1.20999999999998.
Am I making some fundamental error? And one have experience of this? How can I get the same results as the spreadsheet (against which I am validating my calculations).
OK so I updated to include a conversions from Float to Double as suggested in the replies and look at the result! The Double(float_value) conversion seems to add garbage in the lower significance digits of the result.
import UIKit
var str = "Hello, playground"
let y_float: Float = 129.08
let t_float : Float = 130.29
let y: Double = Double(y_float) // results in 129.0800018310547 !!!
let t: Double = Double(t_float) // results in 130.2899932861328
let subtracted : Double = t - y
let returnVal = subtracted / y
So now the question is, any way to make a clean conversion from Float to Double?