Working with Math Routines in C#

Basic math operators—such as plus, minus, and modulus—can get you only so far. It is only a matter of time before you find that you need more robust math routines. C# has access to a set of math routines within the base classes. These are available from within the System.Math namespace. Table 1 presents a number of the math methods available.

The Math class is sealed. A sealed class cannot be used for inheritance. Additionally, all the classes and data members are static, so you can't create an object of type Math. Instead, you use the members and methods with the class name.

Table 1: Math Routines in the Math Class

Method  Returns
Abs  Returns the absolute value of a number.
Ceiling  Returns a value that is the smallest whole number greater than or equal to a given number.
Exp  Returns E raised to a given power. This is the inverse of Log.
Floor  Returns a value that is the largest whole number that is less than or equal to the given number.
IEEERemainder  Returns the result of a division of two specified numbers. (This division operation conforms to the remainder operation stated within Section 5.1 of ANSI/IEEE Std. 754-1985; IEEE Standard for Binary Floating-Point Arithmetic; Institute of Electrical and Electronics Engineers, Inc; 1985.)
Log  Returns a value that is the logarithmic value of the given number.
Log10  Returns a value that is the base 10 logarithm of a given value.
Max  Returns the larger of two values.
Min  Returns the smaller of two values.
Pow  Returns the value of a given value raised to a given power.
Round  Returns a rounded value for a number. You can specify the precision of the rounded number. The number .5 would be rounded down.
Sign  Returns a value indicating the sign of a value. 1 is returned for a negative number, 0 is returned for zero, and 1 is returned for a positive number.
Sqrt  Returns the square root for a given value.
Acos  Returns the value of an angle whose cosine is equal to a given number.
Asin  Returns the value of an angle whose sine is equal to a given number.
Atan  Returns the value of an angle whose tangent is equal to a given number.
Atan2  Returns the value of an angle whose tangent is equal to the quotient of two given numbers.
Cos  Returns a value that is the cosine of a given angle.
Cosh  Returns a value that is the hyperbolic cosine for a given angle.
Sin  Returns the sine for a given angle.
Sinh  Returns the hyperbolic sine for a given angle.
Tan  Returns the tangent of a specified angle.
Tanh  Returns the hyperbolic tangent of a given angle.

The Math class also includes two constants: PI and E. PI returns the value of [PI] as 3.14159265358979323846. The E data member returns the value of the logarithmic base, 2.7182818284590452354.

Most of the math methods in Table 1 are easy to understand. Listing 1 presents a couple of the routines in use.

Listing 1: MathApp.cs — Using Some of the Math Routines

 1:  //  MathApp.cs - Using a Math routine
 2:  //-----------------------------------------------
 3:  using System;
 4:  
 5:  class MathApp
 6:  {
 7:     public static void Main()
 8:     {
 9:        int val2;
10:        char disp;
11:  
12:        for (double ctr = 0.0; ctr <= 10; ctr += .2)
13:        {
14:           val2 = (int) Math.Round( ( 10 * Math.Sin(ctr))) ;
15:           for( int ctr2 = -10; ctr2 <= 10; ctr2++ )
16:           {
17:              if (ctr2 == val2)
18:                 disp = 'X';
19:              else
20:                 disp = ' ';
21:  
22:              Console.Write("{0}", disp);
23:           }
24:           Console.WriteLine(" ");
25:        }
26:     }
27:  }

The following is the output:

          X           
            X         
              X       
                X     
                 X    
                  X   
                   X  
                    X 
                    X 
                    X 
                   X  
                  X   
                 X    
               X      
             X        
           X          
         X            
       X              
      X               
    X                 
  X                   
 X                    
X                     
X                     
X                     
X                     
 X                    
  X                   
    X                 
     X                
       X              
         X            
           X          
             X        
               X      
                 X    
                  X   
                   X  
                    X 
                    X 
                    X 
                   X  
                   X  
                 X    
                X     
              X       
            X         
          X           
        X             
      X               
     X                

This listing maps out the Sin method. A for statement in Lines 12 to 25 loops through double values, incrementing them by .2 each iteration. The sine of this value is obtained using the Math.Sin method in Line 14. The sine is a value from 1.0 to 1.0. To make the display easier, this value is converted to a value from 10 to 10. This conversion is done by multiplying the returned sine value by 10 and then rounding the value with the Math.Round method.

The result of doing the multiplication and rounding is that val2 is a value from 10 to 10. A for loop in Line 15 displays a single line of characters. This line of characters is spaces, with the exception of the character in the position equal to val2. Line 24 prints another space to start a new line. The result of this work is a rough display of a sine curve.

# # #



About the Author

Bradley Jones

Bradley Jones, in addition to managing CodeGuru, Brad! oversees the Developer.com Newtwork of sites including Codeguru, Developer.com, DevX, VBForums, and over a dozen more with a focus on software development and database technologies. His experience includes development in C, C++, VB, some Java, C#, ASP, COBOL, and more as well as having been a developer, consultant, analyst, lead, and much more. His recent books include Teach Yourself the C# Language in 21 Days, Web 2.0 Heroes, and Windows Live Essentials and Services.
Google+ Profile | Linked-In Profile | Facebook Page

Comments

  • Discount Oakley Twenty online store

    Posted by ffoloqfxo on 07/04/2013 04:00pm

    Fake RayBan ,The amalgamation of the extremely comprehensive eye care products on this planet, Oakley sunglasses sale, a global freed from the oldest and quite a few well-known and a lot respected healthcare brands. Each sun shiny day, you will find which i wear Oakley sunglasses, it's not in order to protect their eyes, exposed to us can be the intangible confidence. However, lately glial Oakley sunglasses sales (Frogskin), heat is Oakley led style. Recently, the release the Oakley09 new service preview, delete Frogskin, a narrow product. Oakley Oil Rig ,A good example could be interpreted to the classic type of romantic named Oakley Romeo and Juliet "sunglasses. Maybe you are which kind of person, or a set of sunglasses, it truly is available for you. These sunglasses are actually made to meet the requirements of most personal taste. This will be unfortunately a trendy shapes greatly marked in the year and hot summertime, many fashion brand masters, design taste, without the intent to streamline the full sense of glasses. I can't think what a professional athlete refused Oakley products bring high-definition and open peripheral vision. Oakley Outlet ,Ahead of considering the way the choice of Oakley sunglasses, let us returning to discover why people have to do good thing about Oakley sunglasses. Graphs since you also could see further safety. Oakley Penny Sunglasses strength to weight ratio is amazing, the sensation is surprisingly light. You'll find three suitable to support the lens precise optical alignment of comfort and gratification. Fake ray bans ,Oakley shades of good quality (especially the "surround variety), major safety and solar energy, ultraviolet radiation for the eye to give you, they are ideal for people of every age group. Popular aspects of many, the buzz through history, will look back, so with the retro. Longchamp Pas Cher ,Ranging from materials to design for the framework of the production process, every detail perfect, to create the wearer feel safe. Most girls are generally like the development sari, related to the protection of one's style know a brand image in addition to Oakley sunglasses cheap teenager understand that this manufacturer. Desire to fashion and fashion sunglasses, look into the sale of Oakley sunglasses, there is a one you desire so you, Oakley sunglasses is the greatest choice because of this summer.

    Reply
  • Great Stuff

    Posted by anand_n on 03/20/2004 01:19am

    Keep it up - Brad
    
    Regards,
    Anand N
    Microsoft MVP

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: October 29, 2014 @ 11:00 a.m. ET / 8:00 a.m. PT Are you interested in building a cognitive application using the power of IBM Watson? Need a platform that provides speed and ease for rapidly deploying this application? Join Chris Madison, Watson Solution Architect, as he walks through the process of building a Watson powered application on IBM Bluemix. Chris will talk about the new Watson Services just released on IBM bluemix, but more importantly he will do a step by step cognitive …

  • Packaged application development teams frequently operate with limited testing environments due to time and labor constraints. By virtualizing the entire application stack, packaged application development teams can deliver business results faster, at higher quality, and with lower risk.

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds