Friday, January 22, 2016

Matematika, klasa Math u C# programskom jeziku



Pre se prilikom učenja programiranja u C i C++ programskom jeziku često koristila matematika i zbirke matematičkih zadataka kako bi se kroz matematiku učilo programiranje. Poznavanje matematičkih formula, manipulacije brojevima i poznavanje geometrije je na neki način bio preduslov da bi ste se uopšte i upustili u programiranje. Danas se toliko ne insistira na tome; kad učite C# programski jezik; jedna od najbitnijih matematičkih klasa Math, retko da se i uopšte spominje prilikom edukacije. Jednostavno se podrazumeva da koristite klasu Math kad vam je ona potrebna kao i bilo kakva sporedna klasa .Net Framework-a. Međutim ja vam savetujem da ovu klasu dobro prostudirate jer će te je često koristiti ukoliko se budete bavili ozbiljnim projektima.



( Math klasa, nezaobilazna za matematičke proračune )


Klasa Math je statička klasa, koja se nalazi u System.Math imenskom prostoru, tako da nemate potrebe da uvozite ovu klasu ukoliko već koristite imenski prostor System. Klasa Math vam omogućava da koristite osnovne matematičke funkcije, koje su već testirane i nemate potrebe da vi pišete vaše. Od verzije C# 6.0 vi možete da imenski prostor Math koristite i na ovakav način:

using static System.Math;

Na ovaj način možete pisati kraće konstante i metode klase Math.

WriteLine(PI.ToString()); // Math.PI.ToString() = 3.14159265358979

Pored toga što ne morate razmišljati koliko je tačno PI u vašim proračunima kad koristite klasu Math, isto tako ne morate ni da razmišljate ni koliki je prirodni logaritam, od pre poznat kao hiperbolički logaritam što je logaritam za bazu e, gdje je e iracionalna konstanta, čija je približna vrijednost:

WriteLine(E.ToString()); // E = 2.71828182845905

Koje matematičke metode sadrži klasa Math?


Klasa Math sadrži neke od osnovnih matematički funkcija jer većina matematičkih formula se bazira na skupu istih metoda. Na primer ako želite da izračunate hipotenuzu pravouglog trougla koristiće te više metoda klase Math:

double hipotenuza = Sqrt(Pow(a, 2) + Pow(b, 2));

Ali da krenemo redom. Prva metoda Abs vraća absolutnu vrednost. Jednostavno pozitivan broj vraća kao pozitivni, dok negativni broj takođe vraća u pozitivni.

WriteLine($"abs(-7) = {Abs(-7)}"); // Returns 7

Klasa Math je takođe nezaobilazna ako nameravate da se u programiranju bavite trigonometrijskim funkcijama ili funkcijama ugla.

WriteLine($"Acos(0) = {Acos(0)}");
WriteLine($"Cos(2) = {Cos(2)}");
WriteLine($"Cosh(5) = {Cosh(5)}");

WriteLine($"Asin(0.2) = {Asin(0.2)}");
WriteLine($"Sin(2) = {Sin(2)}");
WriteLine($"Sinh(-5) = {Sinh(-5)}");

WriteLine($"Atan(-5) = {Atan(-5)}");
WriteLine($"Atan2(2,1) = {Atan2(2,1)}");
WriteLine($"Tan(1) = {Tan(1)}");
WriteLine($"Tanh(0.1) = {Tanh(0.1)}");

Pored trigonometrijski funkcija, klasa Math sadrži i metode koje nisu matematičke prirode već isključivo programerske. Na primer zamislite da množite dva velika integer broja čiji rezultat može dovesti do prekoračenja ranga tipa long i prijaviti vam grešku. Možete pokušati ovako nešto.

long number = unchecked(int.MaxValue * int.MaxValue); // Result 1

Ali rezultat nije 1. Za ovakve slučajeve klasa Math ima metodu BigMul, koja će vam prikazati pravi rezultat.

long number = BigMul(int.MaxValue, int.MaxValue); // Result 4611686014132420609

Ili kako da tačno odredite na koji broj želite da zaokružite neki broj. Metode Ceiling i Floor klase Math vam itekako mogu olakšati ovaj posao.

Value           Ceiling           Floor

7.03                8                     7
7.64                8                     7 

0.12                1                     0
-0.12               0                   -1
-7.1                -7                   -8
-7.6                -7                   -8


Međutim kad smo kod zaokruživanja brojeva, ponekad se morate pitati da li na primer broj 1.5 želite zaokružiti na 1 ili na 2. Ili na kojoj decimali broja želite da da zaokružite broj. Metoda Round je u ovom slučaju jednostavno rešenje, ili bi ste sami morali da pišete komleksan kod.

WriteLine($"{Round(123.45)}"); // 123
WriteLine($"{Round(123.45, 1, MidpointRounding.AwayFromZero)}"); // 123.5
WriteLine($"{Round(123.45, 1, MidpointRounding.ToEven)}"); // 123.4

Ili da jednostavno prepustite stvari metodi Truncate:

WriteLine($"Truncate(56.789) = {Truncate(56.789)}"); // 56
WriteLine($"Truncate(-56.789) = {Truncate(-56.789)}"); // -56

Klasa Math sadrži i metode za izračunavanje logaritma:

WriteLine("$"Log(1.2) = {Log(1.2)}");
WriteLine("$"Log(1.2, 0.1) = {Log(1.2, 0.1)}");
WriteLine("$"Log10(50) = {Log10(50)}");

Pretpostavimo da želite da izračunate količnik dva cela broja, ali takođe vam treba i ostatak. Metoda DivRem vam to omogućava na najednostavniji način.

int number1 = 100, number2 = 35, result;
int quotient = DivRem(number1, number2, out result);

WriteLine("number1 = " + number1); // 100
WriteLine("number2 = " + number2); // 35
WriteLine("quotient = " + quotient); // 100 / 35 = 20
WriteLine("The rest of the number: " + result); // 30

U vašim matematičkim proračunima možete doći u situaciju da radite sa modulo brojevima. Međutim šta ako vama treba negativan ostatak. To nećete moći dobiti od modulo dva broja. Klasa Math ima rešenje i za takav slučaj,  jednostavno umesto modulo koristite metodu IEEERemainder:

WriteLine($"IEEERemainder(3, 4) = {IEEERemainder(3, 4)}"); // -1 Different from 3 % 4 = 3    

Ukoliko hoćete da izračunate bilo koji stepen od nekog broja, koristite metodu Pow klase Math.

WriteLine($"Pow(7,2) = {Pow(7, 2)}"); // 7 * 7 = 49

Naravno, ukoliko vam treba koren od nekog broja i za to postoji metoda

WriteLine($"Sqrt(49) = {Sqrt(49)}"); // 49 / 7 = 7

I zadnje metode klase Math su metode Max i Min sa kojima nećete imati potrebu da pišete vlastite metode za izračunavanje maksimalnog i minimalnog broja.

WriteLine($"{Max(123.45, 567.89)}"); // 567.89
WriteLine($"{Min(123.45, 567.89)}"); // 123.45

Sad kad ste upoznati sa svim metodama klase Math, dobro bi bilo da isprogramirate i sledeći program, kako bi se lakše uvek mogli prisetiti kada i kako da koristite klasu Math.

using System;
using static System.Console;
using static System.Math;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MathClass
{
    class Program
    {
        static void Main(string[] args)
        {
            WriteLine("SYSTEM.MATH CLASS" + Environment.NewLine);

            WriteLine("E - Returns the base of the natural logarithm: " + E.ToString()); // E =  2.71828182845905
            WriteLine("PI - Returns PI number: " + PI.ToString() + Environment.NewLine);  // PI = 3.14159265358979

            WriteLine($"Abs - Returns the absolute number: Abs(-7) = {Abs(-7)}" + Environment.NewLine); // 7

            ReadKey();
            Clear();

            WriteLine("Trigonometric functions: " + Environment.NewLine);

            WriteLine("Acos - Returns the angle whose cosine is the specified number:" + Environment.NewLine
                      + $"Acos(0) = {Acos(0)}");
            WriteLine("Cos - Returns the cosine of the specified angle:" + Environment.NewLine
                      + $"Cos(2) = {Cos(2)}");
            WriteLine("Cosh - Returns the hyperbolic cosine of the specified angle:" + Environment.NewLine
                      + $"Cosh(5) = {Cosh(5)}" + Environment.NewLine);

            WriteLine("Asin - Returns the angle whose sine is the specified number:" + Environment.NewLine
                      + $"Asin(0.2) = {Asin(0.2)}");
            WriteLine("Sin - Returns the sine of the specified angle:" + Environment.NewLine
                      + $"Sin(2) = {Sin(2)}");
            WriteLine("Sinh - Returns the hyperbolic sine of the specified angle:" + Environment.NewLine
                      + $"Sinh(-5) = {Sinh(-5)}" + Environment.NewLine);

            WriteLine("Atan - Returns the angle whose tangent is the specified number:" + Environment.NewLine
                      + $"Atan(-5) = {Atan(-5)}");
            WriteLine("Atan2 - Returns the angle whose tangent is the quotient of 2 specified numbers:" + Environment.NewLine
                     + $"Atan2(2,1) = {Atan2(2,1)}");
            WriteLine("Tan - Returns the tangent of the specified angle:" + Environment.NewLine
                      + $"Tan(1) = {Tan(1)}");
            WriteLine("Tanh - Returns the hyperbolic tangent of the specified angle:" + Environment.NewLine
                      + $"Tanh(0.1) = {Tanh(0.1)}" + Environment.NewLine);

            ReadKey();
            Clear();

            WriteLine("BigMul - Produces the full product of two 32-bit numbers:");
            WriteLine($"BigMul(int.MaxValue, int.MaxValue) = {int.MaxValue}*{int.MaxValue} = {BigMul(int.MaxValue, int.MaxValue)}");

            WriteLine(Environment.NewLine + "Ceiling and Floor methods:" + Environment.NewLine);

            decimal[] values = { 7.03m, 7.64m, 0.12m, -0.12m, -7.1m, -7.6m };
            WriteLine("  Value          Ceiling          Floor" + Environment.NewLine);
            foreach (decimal value in values) WriteLine("{0,7} {1,16} {2,14}", value, Ceiling(value), Floor(value));

            ReadKey();
            Clear();
           
            WriteLine(Environment.NewLine + "Round - Round type numbers in many ways:" + Environment.NewLine);

            WriteLine($"Round(123.45) = {Round(123.45)}"); // 123
            WriteLine($"Round(123.45, 1, MidpointRounding.AwayFromZero) = {Round(123.45, 1, MidpointRounding.AwayFromZero)}"); // 123.5
            WriteLine($"Round(123.45, 1, MidpointRounding.ToEven) = {Round(123.45, 1, MidpointRounding.ToEven)}"); // 123.4

            WriteLine(Environment.NewLine + "Truncate - Calculates the integral part of a specified number:" + Environment.NewLine);

            WriteLine($"Truncate(56.789) = {Truncate(56.789)}"); // 56
            WriteLine($"Truncate(-56.789) = {Truncate(-56.789)}"); // -56

            WriteLine(Environment.NewLine + $"Exp - Returns e raised to the specified power. Exp(0.5) = {Exp(0.5)}"
                    + Environment.NewLine);

            WriteLine("Log - Returns the natural (base e) logarithm of a specified number:" + Environment.NewLine
                     + $"Log(1.2) = {Log(1.2)}");
            WriteLine("Log(double, double) - Returns the logarithm of a specified number" + Environment.NewLine 
                     + "in a specified base." + Environment.NewLine
                     + $"Log(1.2, 0.1) = {Log(1.2, 0.1)}");
            WriteLine("Log10 - Returns the base 10 logarithm of a specified number." + Environment.NewLine
                     + $"Log10(50) = {Log10(50)}" + Environment.NewLine);

            ReadKey();
            Clear();

            WriteLine("DivRem - Calculates the quotient of two integers and also returns the remainder in an output parameter.");

            int number1 = 100, number2 = 35, result;
            int quotient = DivRem(number1, number2, out result);

            WriteLine("number1 = " + number1); // 100
            WriteLine("number2 = " + number2); // 35
            WriteLine("quotient = " + quotient); // 100 / 35 = 2
            WriteLine("The rest of the number: " + result ); // 30

            WriteLine(Environment.NewLine + "IEEERemainder - Returns the remainder resulting from"
                      + "the division of a specified number by another specified number.");
            WriteLine($"IEEERemainder(3, 4) = {IEEERemainder(3, 4)}"); // -1 - Different from 3 % 4 = 1

            WriteLine(Environment.NewLine + "Pow - Returns a specified number raised to the specified power:"
                    + Environment.NewLine + $"Pow(7,2) = {Pow(7, 2)}");  // 7 * 7 = 49

            WriteLine(Environment.NewLine + "Sqrt - Returns the square root of a specified number:"
                    + Environment.NewLine + $"Sqrt(49) = {Sqrt(49)}");  // 49 / 7 = 7

            WriteLine(Environment.NewLine + "Maximum and Minimum numbers: ");
            WriteLine($"Max - Returns the larger of two numbers. Max(123.45, 567.89) = {Max(123.45, 567.89)}"); // 567.89
            WriteLine($"Min - Returns the smaller of two numbers. Min(123.45, 567.89) = {Min(123.45, 567.89)}"); // 123.45

            ReadKey();


        }
    }
}

Kad pokrenete navedeni program on će vam prikazati sledeće rezultate:

SYSTEM.MATH CLASS

E - Returns the base of the natural logarithm: 2.71828182845905
PI - Returns PI number: 3.14159265358979

Abs - Returns the absolute number: Abs(-7) = 7

Trigonometric functions:

Acos - Returns the angle whose cosine is the specified number:
Acos(0) = 1.5707963267949
Cos - Returns the cosine of the specified angle:
Cos(2) = -0.416146836547142
Cosh - Returns the hyperbolic cosine of the specified angle:
Cosh(5) = 74.2099485247878

Asin - Returns the angle whose sine is the specified number:
Asin(0.2) = 0.201357920790331
Sin - Returns the sine of the specified angle:
Sin(2) = 0.909297426825682
Sinh - Returns the hyperbolic sine of the specified angle:
Sinh(-5) = -74.2032105777888

Atan - Returns the angle whose tangent is the specified number:
Atan(-5) = -1.37340076694502
Atan2 - Returns the angle whose tangent is the quotient of 2 specified numbers:
Atan2(2,1) = 1.10714871779409

Tan - Returns the tangent of the specified angle:
Tan(1) = 1.5574077246549
Tanh - Returns the hyperbolic tangent of the specified angle:
Tanh(0.1) = 0.0996679946249558

BigMul - Produces the full product of two 32-bit numbers:
BigMul(int.MaxValue, int.MaxValue) = 2147483647*2147483647 = 4611686014132420609

Ceiling and Floor methods:

Value           Ceiling           Floor

7.03                8                     7 

7.64                8                     7 
0.12                1                     0
-0.12               0                   -1
-7.1                -7                   -8
-7.6                -7                   -8

Round - Round type numbers in many ways:
 

Round(123.45) = 123
Round(123.45, 1, MidpointRounding.AwayFromZero) = 123.5
Round(123.45, 1, MidpointRounding.ToEven) = 123.4
 

Truncate - Calculates the integral part of a specified number:

Truncate(56.789) = 56
Truncate(-56.789) = -56

Exp - Returns e raised to the specified power. Exp(0.5) = 1.64872127070013

Log - Returns the natural (base e) logarithm of a specified number:
Log(1.2) = 0.182321556793955
Log(double, double) - Returns the logarithm of a specified number
in a specified base.
Log(1.2, 0.1) = -0.0791812460476248
Log10 - Returns the base 10 logarithm of a specified number.
Log10(50) = 1.69897000433602

DivRem - Calculates the quotient of two integers and also returns the remainder
in an output parameter.

number1 = 100
number2 = 35
quotient = 2
The rest of the number: 30

IEEERemainder - Returns the remainder resulting fromthe division of a specified
number by another specified number.
IEEERemainder(3, 4) = -1

Pow - Returns a specified number raised to the specified power:
Pow(7,2) = 49
 

Sqrt - Returns the square root of a specified number:
Sqrt(49) = 7

Maximum and Minimum numbers:

Max - Returns the larger of two numbers. Max(123.45, 567.89) = 567.89
Min - Returns the smaller of two numbers. Min(123.45, 567.89) = 123.45


Kako to sve izgleda možete pogledati i na video-u:


( C# 6.0 Tutorial - Fundamentals - 35. Math Class )
  

No comments:

Post a Comment