gpt4 book ai didi

c# - 一种实现幂函数的有效方法 : Why Math. Exp(x * Math.Log(n)) 比 Math.Pow() 更快?

转载 作者:行者123 更新时间:2023-11-30 14:30:12 32 4
gpt4 key购买 nike

我正在尝试使用这两种方法在 C# 中解决这个问题:

public double NormalPowerMethod(double x, double toPower)
{
return Math.Pow(x, toPower);
}

public double EfficientPowerMethod(double x, double toPower)
{
return Math.Exp(Math.Log(x) * toPower);
}

I ran a simple test program :

EfficientPower ep = new EfficientPower();
Console.WriteLine("Enter x:");
double x = Double.Parse(Console.ReadLine());
Console.WriteLine("Enter power: ");
int toPower = Int32.Parse(Console.ReadLine());
Stopwatch timer = new Stopwatch();
timer.Start();
Console.WriteLine(string.Format("{0} to the power of {1}= {2}", x,toPower, ep.NormalPowerMethod(x,toPower)));
timer.Stop();
Console.WriteLine("Normal power time =" + timer.ElapsedTicks);

//-------------- efficient
timer.Reset();
timer.Start();
Console.WriteLine(string.Format("Efficient power: {0} to the power of {1}= {2}", x, toPower, ep.EfficientPowerMethod(x, toPower)));
timer.Stop();
Console.WriteLine("Efficient power time =" + timer.ElapsedTicks);

Console.ReadLine();

我注意到了:

  • Math.pow(x,y)Math.Exp(Math.log(x) * y)

例如:

Enter x:
15
Enter power:
26
Normal power: 15 to the power of 26= 3.78767524410635E+30
Normal power time =818
Efficient power: 15 to the power of 26= 3.78767524410634E+30
Efficient power time =533


Enter x:
1024
Enter power:
1024
Normal power: 1024 to the power of 1024= Infinity
Normal power time =810
Efficient power: 1024 to the power of 1024= Infinity
Efficient power time =519

为什么会有这样的行为?我认为更多的计算会更慢?

最佳答案

Math.Pow必须做一些额外的检查,以便它可以返回正确的值如果 x < 0toPower是一个整数。

关于c# - 一种实现幂函数的有效方法 : Why Math. Exp(x * Math.Log(n)) 比 Math.Pow() 更快?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24011424/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com