如何在Swift中乘以数字?

时间:2022-02-05 13:42:29

I am working on a calculator in Swift, but I have a small problem: when multiplying two numbers, I don't have the same results as a regular calculator.

我正在使用Swift中的计算器,但我遇到一个小问题:当乘以两个数字时,我的结果与常规计算器不同。

For example:

In Swift :

在Swift中:

0.333328247070312 * 16 = 5.33325195312499

In a regular calculator:

在常规计算器中:

0.333328247070312 * 16 = 5.333251953

What should I do to get the same results as a regular calculator in Swift?

我应该怎么做才能获得与Swift常规计算器相同的结果?

1 个解决方案

#1


1  

Your "regular calculator" seems wrong or weird in result printing, so, you should not rely on it. I've rechecked your calculation in Python3 which is known to calculate all in binary64 double and print the most exact decimal form:

您的“常规计算器”在结果打印中似乎有误或奇怪,因此,您不应该依赖它。我已经在Python3中重新检查了你的计算,已知它在binary64 double中计算所有并打印出最精确的十进制形式:

>>> 0.333328247070312 * 16
5.333251953124992

it's even more detailed (by one digit) than Swift output. Your output also can't be verified as binary32 calculation, because the latter has ~7 correct decimal digits, and usually isn't printed with more digits. What this calculator is? I'd suppose some Pascal-based tool due to its custom 6-byte float.

它比Swift输出更加详细(一位数)。您的输出也无法验证为binary32计算,因为后者具有~7个正确的十进制数字,并且通常不会打印更多数字。这个计算器是什么?我想一些基于Pascal的工具是由于它的自定义6字节浮点数。

Try to ask your calculator to print the most detailed form. If it fails, throw it away and use a most exact tool to verify, or, if your task is really to get the same result, figure out more details about its processing.

尝试让计算器打印最详细的表格。如果它失败了,扔掉它并使用最精确的工具来验证,或者,如果你的任务真的要得到相同的结果,请弄清楚它的处理的更多细节。

#1


1  

Your "regular calculator" seems wrong or weird in result printing, so, you should not rely on it. I've rechecked your calculation in Python3 which is known to calculate all in binary64 double and print the most exact decimal form:

您的“常规计算器”在结果打印中似乎有误或奇怪,因此,您不应该依赖它。我已经在Python3中重新检查了你的计算,已知它在binary64 double中计算所有并打印出最精确的十进制形式:

>>> 0.333328247070312 * 16
5.333251953124992

it's even more detailed (by one digit) than Swift output. Your output also can't be verified as binary32 calculation, because the latter has ~7 correct decimal digits, and usually isn't printed with more digits. What this calculator is? I'd suppose some Pascal-based tool due to its custom 6-byte float.

它比Swift输出更加详细(一位数)。您的输出也无法验证为binary32计算,因为后者具有~7个正确的十进制数字,并且通常不会打印更多数字。这个计算器是什么?我想一些基于Pascal的工具是由于它的自定义6字节浮点数。

Try to ask your calculator to print the most detailed form. If it fails, throw it away and use a most exact tool to verify, or, if your task is really to get the same result, figure out more details about its processing.

尝试让计算器打印最详细的表格。如果它失败了,扔掉它并使用最精确的工具来验证,或者,如果你的任务真的要得到相同的结果,请弄清楚它的处理的更多细节。