Visual Basic/Simple Arithmetic

From Wikibooks, open books for an open world
< Visual Basic
Jump to: navigation, search

Visual Basic has all of the common arithmetical functions. It does not have complex numbers nor does it allow you to overload operators so manipulating complex numbers or matrices must be done by explicit function and subroutine calls.

Arithmetic Operators[edit]

The operators are infix and take two arguments: arg1 operator arg2 except for unary plus and minus

Numeric Operators[edit]

Operator Comments
+ Adds two numbers. Also concatenates strings but avoid this use because Visual Basic will try to convert the string to a number first and the results might not be what you expect.
- Subtract the second number from the first.
- unary negate the operand.
* Multiply two numbers. The result will be promoted to whatever data type is needed to represent the size of the number if one of the numbers is already that type (see note below about odd behavior).
/ Normal division. Treats both operands as real numbers and returns a real result.
\ Integer division. Be careful with this because the arguments are converted to integers before the division is performed so use this with integer operands unless you comment your code carefully.

Also note that "/" and "*" are evaluated before "\", so (1000 \ 13 * 3) is not equal to ( (1000 \ 13) * 3)

Mod Produces the remainder after integer division. Be careful with this as the interpretation of the modulus operator in mathematics is ambiguous. a Mod b gives the same answer as this expression: a - (a \ b) * b
^ Raises the first operand to the power of the second. In Visual Basic either or both operands may be negative. If all you want is a square or cube it is faster to explcitly multiply the number by itself the appropriate number of times.

For example:

Text2 = Text1 * 5

Will display the value in Text1, multiplied by 5, in Text2. E.g. if Text1 = 4 then Text2 will be equal to 20.

Order of operations[edit]

  • Exponentiation (^)
  • Multiplication and normal division (* and /)
  • Integer division (\)
  • Mod (Mod)
  • Addition and subtraction (+,-)

General hint : If an expression uses more than (+,-,*) use all possible brackets to force the expression to be evaluated the way you are thinking it.

VB odd behavior note[edit]

VB considers "explicitly stated" integral numbers to be of type Integer (which must be between -32768 and 32767) if they are within (-32768, +32767) and gives an error if the result of arithmetic with them is more than 32768. This can be seen by trying

Debug.Print (17000 + 17000)


Debug.Print (17000 * 3)

which both cause an error. This can be solved (in a direct but ugly way) by enclosing numbers in CLng() (Convert to Long) so that

Debug.Print (CLng(17000) + CLng(17000))

or by using the type-declaration character & which specifies a Long constant:

Debug.Print (17000& + 17000&)

neither of which cause an error. To avoid having to think about this, avoid using explicit numbers in code and instead use "Long" variables and constants such as :

  Const TEST_NUM As Long = 17000&
  Debug.Print (TEST_NUM + TEST_NUM)
  Dim TestNumVar As Long
  TestNumVar = 17000
  Debug.Print (TestNumVar + TestNumVar)

Boolean Arithmetic[edit]

Boolean operators use Boolean variables or integer variables where each individual bit is treated as a Boolean. There are six operators:

Operator: Meaning:
Not Negation
And Conjuncton
Or Disjunction (logical addition)
Xor Exclusive Or
Eqv Equivalence
Imp Implication

When you construct logical expressions with these operators you get the following results:

A B A And B A Or B A Xor B A Eqv B A Imp B

Comparison Operators[edit]

These operators, composed of <, > and =, are use to decide whether one value is smaller than, larger than, or equal to another.

For example:

  Dim i
  i = 50
  If i < 0 Then
      MsgBox "i is less than 0" 
  ElseIf i <= 100 And i >= 0 Then
      MsgBox "i is less than or equal to one hundred and greater than or equal to 0"
  ElseIf i > 100 And i < 200 Then
      MsgBox "i is greater than one hundred less than 200"
      MsgBox "i is greater than or equal to 200"
  End if

Caution! Due to the internal structure of floating-point numbers (Single and Double), do not use = or <> to compare them. Instead, use a small value (usually called Epsilon) as a "maximum difference". For example:

  ' This returns False :
  Debug.Print (Sqr(1.234) * Sqr(1.234)) = 1.234
  ' This returns True :
  E = 0.000001
  Debug.Print Abs((Sqr(1.234) * Sqr(1.234)) - 1.234) < E
Operator Meaning
= Equality
<> Inequality
< Less than
> Greater than
>= Greater than or equal to. Or put another way: not less than
<= Less than or equal to. Or put another way: not greater than

Built in Arithmetic Functions[edit]

There are not many native mathematical functions in Visual basic but this doesn't mean that you can't do significant calculations with it.

returns the absolute value of x, that is, it removes a minus sign if there is one. Examples: Abs(3)=3 ; Abs(-3)=3
returns the value ex. e is Euler's constant, the base of natural logarithms.
the Neperian ('Natural', e base) logarithm of x.
not really a mathematical function because it is actually a subroutine. This initializes the random number generator.
produces the next random number in the series. Please read that sentence again! the random numbers aren't really random, they are instead pseudo-random. If you initialize the random number generator with the same number each time you start a program then you will get the same series of values from Rnd()
returns a real number rounded to n decimal places (uses Banker's rounding).
returns plus one if x is positive, minus one if it is negative, zero if x is identically zero. Sgn(-5)=-1 ; Sgn(5)=1 ; Sgn(0)=0
square root of x. Example: Sqr(25)=5. x must be non-negative. Thus Sqr(-25) will generate an error

Derived Functions[edit]

If you want logarithms to some other base you can use this expression:

Log(x, base) = Log(x) / Log(base)

And to calculate the nth root of a number (cube root, ...)

RootN(x, n) = x ^ (1.0 / n)

Trigonometrical Functions[edit]

Visual Basic has the usual simple trigonometric functions, sin, cos, tan, but if you want some of the more unusual ones or inverses you will need to write some simple functions.

Remember that the angles must be supplied as radians

  radians = degrees * pi / 180

  ArcSin(x) = Atn(x / Sqr(-x * x + 1))

  ArcCos(x) = Atn(-x / Sqr(-x * x + 1)) + 2 * Atn(1)

Notice that the range of applicability of these expressions is limited to the range -1<=x<=1.

Here are some more:

Secant Sec(x) = 1 / Cos(x)
Cosecant Cosec(x) = 1 / Sin(x)
Cotangent Cotan(x) = 1 / Tan(x)
Inverse Sine Arcsin(x) = Atn(x / Sqr(-x * x + 1))
Inverse Secant Arcsec(x) = Atn(x / Sqr(x * x - 1)) + Sgn((x) - 1) * (2 * Atn(1))
Inverse Cosecant Arccosec(x) = Atn(x / Sqr(x * x - 1)) + (Sgn(x) - 1) * (2 * Atn(1))
Inverse Cotangent Arccotan(x) = -Atn(x) + 2 * Atn(1)
Hyperbolic Sine HSin(x) = (Exp(x) - Exp(-x)) / 2
Hyperbolic Cosine HCos(x) = (Exp(x) + Exp(-x)) / 2
Hyperbolic Tangent HTan(x) = (Exp(x) - Exp(-x)) / (Exp(x) + Exp(-x))
Hyperbolic Secant HSec(x) = 2 / (Exp(x) + Exp(-x))
Hyperbolic Cosecant HCosec(x) = 2 / (Exp(x) - Exp(-x))
Hyperbolic Cotangent HCotan(x) = (Exp(x) + Exp(-x)) / (Exp(x) - Exp(-x))
Inverse Hyperbolic Sine HArcsin(x) = Log(x + Sqr(x * x + 1))
Inverse Hyperbolic Cosine HArccos(x) = Log(x + Sqr(x * x - 1))
Inverse Hyperbolic Tangent HArctan(x) = Log((1 + x) / (1 - x)) / 2
Inverse Hyperbolic Secant HArcsec(x) = Log((Sqr(-x * x + 1) + 1) / x)
Inverse Hyperbolic Cosecant HArccosec(x) = Log((Sgn(x) * Sqr(x * x + 1) + 1) / x)
Inverse Hyperbolic Cotangent HArccotan(x) = Log((x + 1) / (x - 1)) / 2

The very useful atan2 function (calculate the angle in all four quadrants of a vector) can be simulated like this:

 Public Const Pi As Double = 3.14159265358979
  Public Function Atan2(ByVal y As Double, ByVal x As Double) As Double
    If y > 0 Then
      If x >= y Then
        Atan2 = Atn(y / x)
      ElseIf x <= -y Then
        Atan2 = Atn(y / x) + Pi
        Atan2 = Pi / 2 - Atn(x / y)
      End If
      If x >= -y Then
        Atan2 = Atn(y / x)
      ElseIf x <= y Then
        Atan2 = Atn(y / x) - Pi
        Atan2 = -Atn(x / y) - Pi / 2
      End If
    End If

  End Function

Other functions:

  ASin(x) = Atan2(x, Sqr(1 - x * x))
  ACos(x) = Atan2(Sqr(1 - x * x), x)

Previous: Getting Started Contents Next: Branching