天天看點

Math:處理數學計算的工具

在軟體開發過程中,我們有時候需要進行些數學計算,除了簡單的四則運算外,我們也許會涉及到三角函數、對數等數學應用。.Net提供了System.Math類輔助我們完成工作。

以下代碼示範了Math的基本能力:

System.Console.WriteLine(System.Math.Abs(-12.01));//絕對值

System.Console.WriteLine(System.Math.PI);//圓周率

System.Console.WriteLine(System.Math.Max(12,14));//最大值

System.Console.WriteLine(System.Math.Min(12,14));//最小值

以下代碼描述了Math對資料進行求接近值的不同方式:

System.Console.WriteLine(System.Math.Ceiling(12.34));//最高整數

System.Console.WriteLine(System.Math.Floor(12.34));//最低整數

System.Console.WriteLine(System.Math.Truncate(12.34));//取整

Math提供了對三角函數的處理能力:

System.Console.WriteLine(System.Math.Acos(0.45));//餘弦值

System.Console.WriteLine(System.Math.Asin(0.45));//正弦值

System.Console.WriteLine(System.Math.Atan(0.45));//正切值

System.Console.WriteLine(System.Math.Sin(90));//正弦值

System.Console.WriteLine(System.Math.Sinh(90));//雙曲正弦值

System.Console.WriteLine(System.Math.Tan(90));//正切值

System.Console.WriteLine(System.Math.Tanh(90));//雙曲正切值

Math提供對應對數、幂等計算的方式:

System.Console.WriteLine(System.Math.Log(3, 10));//對數

System.Console.WriteLine(System.Math.Log10(3));//以 10 為底的對

System.Console.WriteLine(System.Math.Pow(2, 10));//次幂

System.Console.WriteLine(System.Math.Sqrt(9));//平方根

以下代碼向我們示範了如何計算五角星每個點的位置:

int r = 50;

System.Drawing.Point[] apt = new System.Drawing.Point[5];

for (int i = 0; i < apt.Length; i++)

{

apt[i] = new System.Drawing.Point(

(int)(20 + r / 2 + Math.Sin(Math.PI * 54.0 / 180) * r *

Math.Sin(Math.PI * (i * 72.0 + 36) / 180)),

Math.Cos(Math.PI * (i * 72.0 + 36) / 180)));

}

System.Drawing.Point[] aptA = new System.Drawing.Point[5];

for (int i = 0; i < aptA.Length; i++)

aptA[i] = new System.Drawing.Point(

(int)(20 + r / 2 + Math.Sin(Math.PI * 14.0 / 180) /

Math.Sin(Math.PI * 54.0 / 180) * r * Math.Sin(Math.PI * (i * 72.0 + 72) / 180)),

Math.Sin(Math.PI * 54.0 / 180) * r * Math.Cos(Math.PI * (i * 72.0 + 72) / 180))

);

Math中最有意思的是Math.Round方法,該方法是将小數值舍入到指定精度,如果你認為這個方法是我們傳統意義上的四舍五入,那你會以下代碼的運作結果會非常驚訝

System.Console.WriteLine(System.Math.Round(3.25, 1));

System.Console.WriteLine(System.Math.Round(3.15, 1));

你會非常驚訝的發現運作結果并不是你所相信的3.3和3.2,而是如圖3.1.16所示:

圖3.1.16

原因是Round的預設精度控制是遵循 IEEE 标準 754 的第 4 節。這種舍入有時稱為就近舍入或四舍六入五成雙。它可以将因單方向持續舍入中點值而導緻的舍入誤差降到最低。說的通俗點就是,逢六必進位,逢五看奇偶,奇進偶不進。

如果我們希望精度的控制和我們目前的國内傳統一緻,請編寫以下代碼:

System.Console.WriteLine(System.Math.Round(3.25, 1, MidpointRounding.AwayFromZero));

System.Console.WriteLine(System.Math.Round(3.15, 1, MidpointRounding.AwayFromZero));

上述代碼的結果則如圖3.1.17所示:

<a href="http://blog.51cto.com/attachment/201203/224310402.jpg" target="_blank"></a>

圖3.1.17

本文轉自shyleoking 51CTO部落格,原文連結:http://blog.51cto.com/shyleoking/805146

繼續閱讀