![](/img/trans.png)
[英]An efficient way to implement power function: Why Math.Exp(x * Math.Log(n)) is faster than Math.Pow()?
[英]Math.Pow() vs Math.Exp() C# .Net
任何人都可以解釋在C#和.net中使用Math.Pow()
和Math.Exp()
之間的區別嗎?
Exp()
只是使用自身作為指數給一個數字嗎?
Math.Exp(x)
是e x 。 (見http://en.wikipedia.org/wiki/E_(mathematical_constant) 。)
Math.Pow(a, b)
是b 。
Math.Pow(Math.E, x)
和Math.Exp(x)
是相同的,但第二個是使用e作為基礎時使用的慣用語。
只需快速擴展pswg的Benchmark貢獻 -
我希望看到另外一個比較,相當於10 ^ x ==> e ^(x * ln(10)),或{double ln10 = Math.Log(10.0); y = Math.Exp(x * ln10);}
{double ln10 = Math.Log(10.0); y = Math.Exp(x * ln10);}
這是我得到的:
Operation Time
Math.Exp(x) 180 ns (nanoseconds)
Math.Pow(y, x) 440 ns
Math.Exp(x*ln10) 160 ns
Times are per 10x calls to Math functions.
我不明白為什么在進入Exp()
之前在循環中包含乘法的時間始終產生更短的時間,除非此代碼中存在錯誤,或者算法是否依賴於值?
該計划如下。
namespace _10X {
public partial class Form1 : Form {
int nLoops = 1000000;
int ix;
// Values - Just to not always use the same number, and to confirm values.
double[] x = { 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5 };
public Form1() {
InitializeComponent();
Proc();
}
void Proc() {
double y;
long t0;
double t1, t2, t3;
t0 = DateTime.Now.Ticks;
for (int i = 0; i < nLoops; i++) {
for (ix = 0; ix < x.Length; ix++)
y = Math.Exp(x[ix]);
}
t1 = (double)(DateTime.Now.Ticks - t0) * 1e-7 / (double)nLoops;
t0 = DateTime.Now.Ticks;
for (int i = 0; i < nLoops; i++) {
for (ix = 0; ix < x.Length; ix++)
y = Math.Pow(10.0, x[ix]);
}
t2 = (double)(DateTime.Now.Ticks - t0) * 1e-7 / (double)nLoops;
double ln10 = Math.Log(10.0);
t0 = DateTime.Now.Ticks;
for (int i = 0; i < nLoops; i++) {
for (ix = 0; ix < x.Length; ix++)
y = Math.Exp(x[ix] * ln10);
}
t3 = (double)(DateTime.Now.Ticks - t0) * 1e-7 / (double)nLoops;
textBox1.Text = "t1 = " + t1.ToString("F8") + "\r\nt2 = " + t2.ToString("F8")
+ "\r\nt3 = " + t3.ToString("F8");
}
private void btnGo_Click(object sender, EventArgs e) {
textBox1.Clear();
Proc();
}
}
}
所以我想我會使用Math.Exp(x * ln10)
直到有人發現錯誤...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.