C sharp - mathematical function

<p>In C#, a <strong>mathematical function</strong> typically refers to a method that performs a specific math-related operation. This can range from simple arithmetic (like addition or multiplication) to more complex operations (like trigonometric functions or logarithms).</p> <h3>1. <strong>Built-in Math Functions (System.Math)</strong></h3> <p>C# provides a <code>Math</code> class in the <code>System</code> namespace, which includes many static methods for mathematical operations.</p> <h2>Common Examples:</h2> <pre><code class="language-csharp">using System; class Program { static void Main() { double a = 9; double b = -5; Console.WriteLine(Math.Sqrt(a)); // Square root: 3 Console.WriteLine(Math.Abs(b)); // Absolute value: 5 Console.WriteLine(Math.Pow(2, 3)); // 2^3 = 8 Console.WriteLine(Math.Sin(Math.PI / 2)); // sin(90&deg;) = 1 Console.WriteLine(Math.Log(100)); // Natural log of 100 } } </code></pre> <blockquote> <p>The <code>Math</code> class supports types like <code>double</code> and <code>decimal</code> but not directly <code>float</code>. You can cast if needed.</p> </blockquote> <h3>2. <strong>Custom Mathematical Functions</strong></h3> <p>You can define your own functions using methods:</p> <pre><code class="language-csharp">class Program { // A method that computes the square of a number static double Square(double x) { return x * x; } static void Main() { double num = 4; Console.WriteLine(Square(num)); // Output: 16 } } </code></pre> <h3>3. <strong>Math with Delegates or Func</strong></h3> <p>You can pass math functions as parameters using <code>Func&lt;T&gt;</code>:</p> <pre><code class="language-csharp">using System; class Program { static double ApplyFunction(Func&lt;double, double&gt; func, double value) { return func(value); } static void Main() { double result = ApplyFunction(Math.Sqrt, 25); Console.WriteLine(result); // Output: 5 } } </code></pre> <h3>&nbsp;</h3> <ul> <li> <p>Use <code>System.Math</code> for built-in functions like <code>Math.Sqrt()</code>, <code>Math.Pow()</code>, etc.</p> </li> <li> <p>Define custom math functions using methods.</p> </li> <li>&nbsp;</li> </ul> <p>&nbsp;</p>