2

我的 C# 程序遇到了一些速度问题,并确定此百分比计算导致速度变慢。计算很简单,n/d * 100。分子和分母都可以是任何整数。分子永远不会大于分母,也永远不会是负数。因此,结果始终为 0-100。现在,这是通过简单地使用浮点数学来完成的,而且速度有点慢,因为它被计算了数千万次。我真的不需要比最接近的 0.1% 更准确的东西。而且,我只是使用这个计算值来查看它是否大于一个固定的常数值。我在想一切都应该保持为整数,所以精度为 0.1 的范围是 0-1000。有没有什么方法可以在没有浮点数学的情况下计算这个百分比?

这是我用于计算的循环:

for (int i = 0; i < simulationList.Count; i++)
{
    for (int j = i + 1; j < simulationList.Count; j++)
    {
        int matches = GetMatchCount(simulationList[i], simulationList[j]);
        if ((float)matches / (float)simulationList[j].Catchments.Count > thresPercent)
        {
            simulationList[j].IsOverThreshold = true;
        }
    }
}
4

3 回答 3

6

代替n/d > c,您可以使用n > d * c(假设d > 0)。
c是您要比较的常数值。)

这样你根本不需要除法。

但是,请注意溢出。

于 2010-04-11T00:51:03.183 回答
0

如果您的单位是十分之一而不是一个,那么您可以使用整数算术获得 0.1 精度:

代替:

for (...)
{
    float n = ...;
    float d = ...;

    if (n / d > 1.4) // greater than 140% ?

...做类似的事情:

for (...)
{
    int n = 10 * ...;
    int d = ...;
    if (n / d > 14) // greater than 140% ?
于 2010-04-11T01:21:12.120 回答
0

而不是写

if ((float)matches / (float)simulationList[j].Catchments.Count > thresPercent)

写这个:

if (matches * theresPercent_Denominator > simulationList[j].Catchments.Count * thresPercent_Numerator)

这样,您就摆脱了浮点数。

注意:thresPercent可以表示为thresPercent_Numerator / theresPercent_Denominator,只要是有理数。)我认为这是PC上的最佳方式。对于其他一些平台,如果 theresPercent_Denominator 和/或 thresPercent_Numerator 是 2 的幂,您可以通过左移或右移进一步优化它。(通常左移就足够了,但可能需要通过将等式重新排列为除法来使用右移,以防止溢出)

于 2015-02-03T08:37:55.773 回答