在objective-c中相乘时出现意外行为

时间:2013-07-09 12:48:16

标签: objective-c math floating-point

目前,我有两个双打,一个是税收减免价格和税率。

价格:9.79(基本上11但不含税) 税:11%

现在我需要做的是再次获得含税税,所以我这样做:

// Tax exclusive test
double taxRate = 0.11;
double priceWithTax = 11;
double priceWithoutTax = priceWithTax * (1.0 - taxRate);

NSLog(@"priceWithoutTax = %f", priceWithoutTax);

double result = priceWithoutTax * (1 + taxRate);

NSLog(@"Result: %f", result);

但是在执行时我输出了它:

priceWithoutTax = 9.790000
Result: 10.866900

预期产量将再次为11。如果有人能提供帮助那就太棒了,我查了很多关于浮点精度的资料,但我似乎无法找到答案。

提前致谢!

更新(Bathsheba回答后的新代码)

// Tax exclusive test
double taxRate = 0.11;
double priceWithTax = 11;
double priceWithoutTax = priceWithTax * (1.0 - taxRate);

NSLog(@"priceWithoutTax = %f", priceWithoutTax);

double result = priceWithoutTax / (1 - taxRate);

NSLog(@"Result: %f", result);

结果:

priceWithoutTax = 9.790000
Result: 11.000000

2 个答案:

答案 0 :(得分:3)

您的数学不正确:您需要double result = priceWithoutTax / (1.0 - taxRate);

松散地说,浮点精度只能归咎于第14个有效数字(双数)中的错误。

答案 1 :(得分:3)

芭丝谢芭的回答是不正确的。他的结果为您提供了一致的答案,但您的问题是您试图采取包含税收的价格,并在没有税收的情况下计算该项目的价格。为此,芭丝谢芭的数学不正确。

double result = priceWithoutTax * (1 + taxRate);是计算priceWithTax的正确方法。

E.g。一件价值10美元不含税和5%税的衬衫将花费你总共10.50美元

double priceWithoutTax = priceWithTax * (1.0 - taxRate);是用于从priceWithTax计算priceWithoutTax的不正确的公式。使用与10美元衬衫相同的示例,插入此公式将为您提供priceWithoutTax = $10.50 * (1.0 - 0.05) = $9.975。你知道这是错误的答案,因为你知道这件衬衫在没有税的情况下花费10美元。

计算priceWithoutTax的正确方法:double priceWithoutTax = priceWithTax / (1.0 + taxRate);

再次仔细检查衬衫。 priceWithoutTax = $10.50 / (1.0 + 0.05) = $10