You are on page 1of 26

Mathematical functions

Visual Studio .NET provides an easy way of performing mathematical functions, such as addi-
tion, subtraction, multiplication, division, exponentiation, integer division, and finding a remain-
der. For all other tasks, you can utilize the System.Math class.

Basic mathematical operations


.NET offers common operators to facilitate the basic mathematical functions, such as:
· Addition (+)
· Subtraction (-)
· Multiplication (*)
· Division (/)
· Exponentiation (^)
· Integer Division (\)
· Finding the remainder (Mod)

Arithmetic Operators (Visual Basic)

+ Operator (Visual Basic)

Adds two numbers or returns the positive value of a numeric expression. Can also be used to concate-
nate two string expressions.

Example
The following example uses the + operator to add numbers. If the operands are both numeric,
Visual Basic computes the arithmetic result. The arithmetic result represents the sum of the two
operands.
VB

Dim sumNumber As Integer


sumNumber = 2 + 2
sumNumber = 4257.04 + 98112
' The preceding statements set sumNumber to 4 and 102369.

You can also use the + operator to concatenate strings. If the operands are both strings, Visual
Basic concatenates them. The concatenation result represents a single string consisting of the
contents of the two operands one after the other.
If the operands are of mixed types, the result depends on the setting of the Option Strict State-
ment. The following example illustrates the result when Option Strict is On.
VB
Option Strict On
VB
Dim var1 As String = "34"
Dim var2 As Integer = 6
Dim concatenatedNumber As Integer = var1 + var2

VB
' The preceding statement generates a COMPILER ERROR.
The following example illustrates the result when Option Strict is Off.
VB
Option Strict Off
VB
Dim var1 As String = "34"
Dim var2 As Integer = 6
Dim concatenatedNumber As Integer = var1 + var2

VB
' The preceding statement returns 40 after the string in var1 is
' converted to a numeric value. This might be an unexpected result.

To eliminate ambiguity, you should use the & operator instead of + for concatenation.

- Operator (Visual Basic)


Returns the difference between two numeric expressions or the negative value of a numeric expression.

Example
The following example uses the – operator to calculate and return the difference between two
numbers, and then to negate a number.
VB
Dim binaryResult As Double = 459.35 - 334.9
Dim unaryResult As Double = -334.9
Following the execution of these statements, binaryResult contains 124.45 and unaryResult
contains –334.90.

* Operator (Visual Basic)


Example
This example uses the * operator to multiply two numbers. The result is the product of the two
operands.
VB

Dim testValue As Double


testValue = 2 * 2
' The preceding statement sets testValue to 4.
testValue = 459.35 * 334.9
' The preceding statement sets testValue to 153836.315.

/ Operator (Visual Basic)

Divides two numbers and returns a floating-point result.

Example
This example uses the / operator to perform floating-point division. The result is the quotient of
the two operands.
VB

Dim resultValue As Double


resultValue = 10 / 4
resultValue = 10 / 3
The expressions in the preceding example return values of 2.5 and 3.333333.
Note that the result is always floating-point (Double), even though both operands are integer
constants.

\ Operator (Visual Basic)

Divides two numbers and returns an integer result.

Example
The following example uses the \ operator to perform integer division. The result is an integer
that represents the integer quotient of the two operands, with the remainder discarded.
VB

Dim resultValue As Integer


resultValue = 11 \ 4
resultValue = 9 \ 3
resultValue = 100 \ 3
resultValue = 67 \ -3
The expressions in the preceding example return values of 2, 3, 33, and -22, respectively.

Mod Operator (Visual Basic)

Divides two numbers and returns only the remainder.

Example
The following example uses the Mod operator to divide two numbers and return only the remain-
der. If either number is a floating-point number, the result is a floating-point number that repre-
sents the remainder.
VB

Console.WriteLine(10 Mod 5)
' Output: 0
Console.WriteLine(10 Mod 3)
' Output: 1
Console.WriteLine(-10 Mod 3)
' Output: -1
Console.WriteLine(12 Mod 4.3)
' Output: 3.4
Console.WriteLine(12.6 Mod 5)
' Output: 2.6
Console.WriteLine(47.9 Mod 9.35)
' Output: 1.15

^ Operator (Visual Basic)


Raises a number to the power of another number.
Syntax
number ^ exponent

Parts
number
Required. Any numeric expression.
exponent
Required. Any numeric expression.

Result
The result is number raised to the power of exponent, always as a Double value.

Supported Types
Double. Operands of any different type are converted to Double.

Remarks
Visual Basic always performs exponentiation in the Double Data Type.
The value of exponent can be fractional, negative, or both.

When more than one exponentiation is performed in a single expression, the ^ operator is evalu-
ated as it is encountered from left to right.
 Note

The ^ operator can be overloaded, which means that a class or structure can redefine its behav-
ior when an operand has the type of that class or structure. If your code uses this operator on
such a class or structure, be sure you understand its redefined behavior. For more information,
see Operator Procedures.

Example
The following example uses the ^ operator to raise a number to the power of an exponent. The
result is the first operand raised to the power of the second.
VB

Dim exp1, exp2, exp3, exp4, exp5, exp6 As Double


exp1 = 2 ^ 2
exp2 = 3 ^ 3 ^ 3
exp3 = (-5) ^ 3
exp4 = (-5) ^ 4
exp5 = 8 ^ (1.0 / 3.0)
exp6 = 8 ^ (-1.0 / 3.0)
The preceding example produces the following results:
exp1 is set to 4 (2 squared).
exp2 is set to 19683 (3 cubed, then that value cubed).
exp3 is set to -125 (-5 cubed).
exp4 is set to 625 (-5 to the fourth power).
exp5 is set to 2 (cube root of 8).
exp6 is set to 0.5 (1.0 divided by the cube root of 8).
Note the importance of the parentheses in the expressions in the preceding example. Because of
operator precedence, Visual Basic normally performs the ^ operator before any others, even the
unary – operator. If exp4 and exp6 had been calculated without parentheses, they would have
produced the following results:
exp4 = -5 ^ 4 would be calculated as –(5 to the fourth power), which would result in -625.
exp6 = 8 ^ -1.0 / 3.0 would be calculated as (8 to the –1 power, or 0.125) divided by 3.0,
which would result in 0.041666666666666666666666666666667.

^= Operator (Visual Basic)


Syntax
variableorproperty ^= expression

Parts
variableorproperty
Required. Any numeric variable or property.
expression
Required. Any numeric expression.

Remarks
The element on the left side of the ^= operator can be a simple scalar variable, a property, or an
element of an array. The variable or property cannot be ReadOnly.
The ^= operator first raises the value of the variable or property (on the left-hand side of the op-
erator) to the power of the value of the expression (on the right-hand side of the operator). The
operator then assigns the result of that operation back to the variable or property.
Visual Basic always performs exponentiation in the Double Data Type. Operands of any differ-
ent type are converted to Double, and the result is always Double.
The value of expression can be fractional, negative, or both.

Overloading
The ^ Operator can be overloaded, which means that a class or structure can redefine its behav-
ior when an operand has the type of that class or structure. Overloading the ^ operator affects the
behavior of the ^= operator. If your code uses ^= on a class or structure that overloads ^, be sure
you understand its redefined behavior.

Example
The following example uses the ^= operator to raise the value of one Integer variable to the
power of a second variable and assign the result to the first variable.
VB

Dim var1 As Integer = 10


Dim var2 As Integer = 3
var1 ^= var2
' The value of var1 is now 1000.

However, for other operations, you can use the methods available in the System.Math class.

System.Math class members


Some of the members of the System.Math class include the following:
· Trigonometric functions (Sin, Cos, Tan, etc)
· Logarithmic functions (Log and Log10)
· Constants (PI and E)
· Power functions (Exp, Pow, and Sqrt)
· Boundary functions (Floor, Ceiling)
· Comparative functions (Max, Min)
· Sign-related functions (Abs)
Math Functions (Visual Basic)
The following table lists methods of the System.Math class. You can use these in a Visual Basic program.
The following table lists methods of the System.Math class. You can use these in a Visual Basic
program.
.NET Framework
Description
method

Abs Returns the absolute value of a number.

Acos Returns the angle whose cosine is the specified number.

Asin Returns the angle whose sine is the specified number.

Atan Returns the angle whose tangent is the specified number.

Atan2 Returns the angle whose tangent is the quotient of two specified numbers.

BigMul Returns the full product of two 32-bit numbers.

Returns the smallest integral value that's greater than or equal to the specified
Ceiling
Decimal or Double.

Cos Returns the cosine of the specified angle.

Cosh Returns the hyperbolic cosine of the specified angle.

Returns the quotient of two 32-bit or 64-bit signed integers, and also returns the
DivRem
remainder in an output parameter.

Exp Returns e (the base of natural logarithms) raised to the specified power.

Returns the largest integer that's less than or equal to the specified Decimal or
Floor
Double number.

Returns the remainder that results from the division of a specified number by
IEEERemainder
another specified number.

Log Returns the natural (base e) logarithm of a specified number or the logarithm of
.NET Framework
Description
method

a specified number in a specified base.

Log10 Returns the base 10 logarithm of a specified number.

Max Returns the larger of two numbers.

Min Returns the smaller of two numbers.

Pow Returns a specified number raised to the specified power.

Returns a Decimal or Double value rounded to the nearest integral value or to


Round
a specified number of fractional digits.

Sign Returns an Integer value indicating the sign of a number.

Sin Returns the sine of the specified angle.

Sinh Returns the hyperbolic sine of the specified angle.

Sqrt Returns the square root of a specified number.

Tan Returns the tangent of the specified angle.

Tanh Returns the hyperbolic tangent of the specified angle.

Truncate Calculates the integral part of a specified Decimal or Double number.

To use these functions without qualification, import the System.Math namespace into your
project by adding the following code to the top of your source file:
Imports System.Math

Example
This example uses the Abs method of the Math class to compute the absolute value of a number.
' Returns 50.3.
Dim MyNumber1 As Double = Math.Abs(50.3)
' Returns 50.3.
Dim MyNumber2 As Double = Math.Abs(-50.3)

Example
This example uses the Atan method of the Math class to calculate the value of pi.
Public Function GetPi() As Double
' Calculate the value of pi.
Return 4.0 * Math.Atan(1.0)
End Function

Example
This example uses the Cos method of the Math class to return the cosine of an angle.
Public Function Sec(ByVal angle As Double) As Double
' Calculate the secant of angle, in radians.
Return 1.0 / Math.Cos(angle)
End Function

Example
This example uses the Exp method of the Math class to return e raised to a power.
Public Function Sinh(ByVal angle As Double) As Double
' Calculate hyperbolic sine of an angle, in radians.
Return (Math.Exp(angle) - Math.Exp(-angle)) / 2.0
End Function

Example
This example uses the Log method of the Math class to return the natural logarithm of a number.
Public Function Asinh(ByVal value As Double) As Double
' Calculate inverse hyperbolic sine, in radians.
Return Math.Log(value + Math.Sqrt(value * value + 1.0))
End Function

Example
This example uses the Round method of the Math class to round a number to the nearest integer.
' Returns 3.
Dim MyVar2 As Double = Math.Round(2.8)

Example
This example uses the Sign method of the Math class to determine the sign of a number.
' Returns 1.
Dim MySign1 As Integer = Math.Sign(12)
' Returns -1.
Dim MySign2 As Integer = Math.Sign(-2.4)
' Returns 0.
Dim MySign3 As Integer = Math.Sign(0)

Example
This example uses the Sin method of the Math class to return the sine of an angle.
Public Function Csc(ByVal angle As Double) As Double
' Calculate cosecant of an angle, in radians.
Return 1.0 / Math.Sin(angle)
End Function

Example
This example uses the Sqrt method of the Math class to calculate the square root of a number.
' Returns 2.
Dim MySqr1 As Double = Math.Sqrt(4)
' Returns 4.79583152331272.
Dim MySqr2 As Double = Math.Sqrt(23)
' Returns 0.
Dim MySqr3 As Double = Math.Sqrt(0)
' Returns NaN (not a number).
Dim MySqr4 As Double = Math.Sqrt(-4)

Example
This example uses the Tan method of the Math class to return the tangent of an angle.
Public Function Ctan(ByVal angle As Double) As Double
' Calculate cotangent of an angle, in radians.
Return 1.0 / Math.Tan(angle)
End Function

Requirements
Class: Math
Namespace: System

Example
    Private Sub PerformMathFunctions()

        Dim i As Integer

        i = Math.Pow(2, 3)
        MessageBox.Show(i)

        i = Math.Sqrt(16)
        MessageBox.Show(i)

        i = Math.Round(5.34444)
        MessageBox.Show(i)

    End Sub

How it works
First, I define an integer type variable i. Then, I assign the value of 2 taken to the third power and
display the result in the message box (the value displayed is 8). The value of i is then set to the
value of the square root of 16, and its value is displayed in the message box (the value displayed
is 4). And finally, I set the value of the variable i to the result of rounding the number 5.34444
and show the result in the message box (the value displayed is 5).
VB.NET program that computes absolute values

Module Module1
Sub Main()
' Absolute values of integers.
Dim value1 As Integer = -1000
Dim value2 As Integer = 20
Dim abs1 As Integer = Math.Abs(value1)
Dim abs2 As Integer = Math.Abs(value2)

Console.WriteLine(value1)
Console.WriteLine(abs1)
Console.WriteLine(value2)
Console.WriteLine(abs2)

' Absolute values of doubles.


Dim value3 As Double = -100.123
Dim value4 As Double = 20.2
Dim abs3 As Double = Math.Abs(value3)
Dim abs4 As Double = Math.Abs(value4)

Console.WriteLine(value3)
Console.WriteLine(abs3)
Console.WriteLine(value4)
Console.WriteLine(abs4)
End Sub
End Module

Output

-1000
1000
20
20
-100.123
100.123
20.2
20.2

Operator Precedence in Visual Basic


When several operations occur in an expression, each part is evaluated and resolved in a prede-
termined order called operator precedence.

Precedence Rules
When expressions contain operators from more than one category, they are evaluated according
to the following rules:
· The arithmetic and concatenation operators have the order of precedence described in the
following section, and all have greater precedence than the comparison, logical, and bit-
wise operators.
· All comparison operators have equal precedence, and all have greater precedence than
the logical and bitwise operators, but lower precedence than the arithmetic and concate-
nation operators.
· The logical and bitwise operators have the order of precedence described in the following
section, and all have lower precedence than the arithmetic, concatenation, and compari-
son operators.
· Operators with equal precedence are evaluated left to right in the order in which they ap-
pear in the expression.

Precedence Order
Operators are evaluated in the following order of precedence:
Await Operator
Await
Arithmetic and Concatenation Operators
Exponentiation (^)
Unary identity and negation (+, –)
Multiplication and floating-point division (*, /)
Integer division (\)
Modulus arithmetic (Mod)
Addition and subtraction (+, –)
String concatenation (&)
Arithmetic bit shift (<<, >>)
Comparison Operators
All comparison operators (=, <>, <, <=, >, >=, Is, IsNot, Like, TypeOf...Is)
Logical and Bitwise Operators
Negation (Not)
Conjunction (And, AndAlso)
Inclusive disjunction (Or, OrElse)
Exclusive disjunction (Xor)
Comments
The = operator is only the equality comparison operator, not the assignment operator.
The string concatenation operator (&) is not an arithmetic operator, but in precedence it is
grouped with the arithmetic operators.
The Is and IsNot operators are object reference comparison operators. They do not compare the
values of two objects; they check only to determine whether two object variables refer to the
same object instance.

Associativity
When operators of equal precedence appear together in an expression, for example multiplication
and division, the compiler evaluates each operation as it encounters it from left to right. The fol-
lowing example illustrates this.
Dim n1 As Integer = 96 / 8 / 4
Dim n2 As Integer = (96 / 8) / 4
Dim n3 As Integer = 96 / (8 / 4)

The first expression evaluates the division 96 / 8 (which results in 12) and then the division 12 /
4, which results in three. Because the compiler evaluates the operations for n1 from left to right,
the evaluation is the same when that order is explicitly indicated for n2. Both n1 and n2 have a
result of three. By contrast, n3 has a result of 48, because the parentheses force the compiler to
evaluate 8 / 4 first.
Because of this behavior, operators are said to be left associative in Visual Basic.

Overriding Precedence and Associativity


You can use parentheses to force some parts of an expression to be evaluated before others. This
can override both the order of precedence and the left associativity. Visual Basic always per-
forms operations that are enclosed in parentheses before those outside. However, within paren-
theses, it maintains ordinary precedence and associativity, unless you use parentheses within the
parentheses. The following example illustrates this.
Dim a, b, c, d, e, f, g As Double
a = 8.0
b = 3.0
c = 4.0
d = 2.0
e = 1.0
f = a - b + c / d * e
' The preceding line sets f to 7.0. Because of natural operator
' precedence and associativity, it is exactly equivalent to the
' following line.
f = (a - b) + ((c / d) * e)
' The following line overrides the natural operator precedence
' and left associativity.
g = (a - (b + c)) / (d * e)
' The preceding line sets g to 0.5.
2
A baker uses eggs to bake cakes. Eggs are sold in packs of six eggs per
pack. Write a program to calculate the number of packs to buy if the
baker needs 200 eggs.
(b) Write a program to carry out the above task.
Question

3 The flowchart inputs an integer. The predefined function DIV gives the integer result of the di-
vision, e.g. Y 10 DIV 3 gives the value Y = 3. The predefined function MOD gives the
value of the remainder, e.g. Y 10 MOD 3 gives the value Y = 1.

You might also like