谁能解释在 C# 和 .net 中使用Math.Pow()
and之间的区别?Math.Exp()
只是Exp()
用自己作为指数来取一个数字吗?
Math.Exp(x)
是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);}
这是我所拥有的:
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)
直到有人发现这个错误......