簡體   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