繁体   English   中英

Math.Pow()vs Math.Exp()C#.Net

[英]Math.Pow() vs Math.Exp() C# .Net

任何人都可以解释在C#和.net中使用Math.Pow()Math.Exp()之间的区别吗?

Exp()只是使用自身作为指数给一个数字吗?

Math.Pow计算对一些xy x y。

Math.Exp为某些x计算e x ,其中e欧拉数

请注意,虽然Math.Pow(Math.E, d)产生与Math.Exp(d)相同的结果,但快速基准测试比较显示Math.Exp执行速度大约是Math.Pow两倍:

Trial Operations       Pow       Exp
    1       1000 0.0002037 0.0001344 (seconds)
    2     100000 0.0106623 0.0046347 
    3   10000000 1.0892492 0.4677785 
Math.Pow(Math.E,n) = Math.Exp(n)  //of course this is not actual code, just a human equation.

更多信息: Math.PowMath.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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM