Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikibooksThe Free Textbook Project
Search

Visual Basic/Simple Arithmetic

From Wikibooks, open books for an open world
<Visual Basic

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 |edit source]

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

Numeric Operators

[edit |edit source]
OperatorComments
+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.
- unarynegate 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)

ModProduces 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 |edit source]
  • 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 |edit source]

VB considers "explicitly stated" integral numbers to be of typeInteger (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)

or

Debug.Print(17000*3)

which both cause an error. This can be solved (in a direct but ugly way) by enclosing numbers inCLng() (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 :

ConstTEST_NUMAsLong=17000&Debug.Print(TEST_NUM+TEST_NUM)DimTestNumVarAsLongTestNumVar=17000Debug.Print(TestNumVar+TestNumVar)

Boolean Arithmetic

[edit |edit source]

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

Operator:Meaning:
NotNegation
AndConjuncton
OrDisjunction (logical addition)
XorExclusive Or
EqvEquivalence
ImpImplication

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

ABA And BA Or BA Xor BA Eqv BA Imp B
TTTTFTT
TFFTTFF
FTFTTFT
FFFFFTT

Comparison Operators

[edit |edit source]

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

For example:

Dimii=50Ifi<0ThenMsgBox"i is less than 0"ElseIfi<=100Andi>=0ThenMsgBox"i is less than or equal to one hundred and greater than or equal to 0"ElseIfi>100Andi<200ThenMsgBox"i is greater than one hundred less than 200"ElseMsgBox"i is greater than or equal to 200"Endif

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.000001Debug.PrintAbs((Sqr(1.234)*Sqr(1.234))-1.234)<E
OperatorMeaning
=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 |edit source]

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

Abs(x)
returns the absolute value of x, that is, it removes a minus sign if there is one. Examples: Abs(3)=3 ; Abs(-3)=3
Exp(x)
returns the value ex. e is Euler's constant, the base of natural logarithms.
Log(x)
theNeperian ('Natural', e base) logarithm ofx.
Randomize(x)
not really a mathematical function because it is actually a subroutine. This initializes the random number generator.
Rnd(x)
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 fromRnd()
Round(x,n)
returns a real number rounded ton decimal places (uses Banker's rounding).
Sgn(x)
returns plus one ifx is positive, minus one if it is negative, zero ifx is identically zero. Sgn(-5)=-1 ; Sgn(5)=1 ; Sgn(0)=0
Sqr(x)
square root ofx. Example: Sqr(25)=5.x must be non-negative. Thus Sqr(-25) will generate an error

Derived Functions

[edit |edit source]

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 |edit source]

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 asradians

radians=degrees*pi/180ArcSin(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:

SecantSec(x) = 1 / Cos(x)
CosecantCosec(x) = 1 / Sin(x)
CotangentCotan(x) = 1 / Tan(x)
Inverse SineArcsin(x) = Atn(x / Sqr(-x * x + 1))
Inverse CosineArccos(x) = Atn(-x / Sqr(-x * x + 1)) + 2 * Atn(1)
Inverse SecantArcsec(x) = Atn(x / Sqr(x * x - 1)) + Sgn((x) - 1) * (2 * Atn(1))
Inverse CosecantArccosec(x) = Atn(x / Sqr(x * x - 1)) + (Sgn(x) - 1) * (2 * Atn(1))
Inverse CotangentArccotan(x) = -Atn(x) + 2 * Atn(1)
Hyperbolic SineHSin(x) = (Exp(x) - Exp(-x)) / 2
Hyperbolic CosineHCos(x) = (Exp(x) + Exp(-x)) / 2
Hyperbolic TangentHTan(x) = (Exp(x) - Exp(-x)) / (Exp(x) + Exp(-x))
Hyperbolic SecantHSec(x) = 2 / (Exp(x) + Exp(-x))
Hyperbolic CosecantHCosec(x) = 2 / (Exp(x) - Exp(-x))
Hyperbolic CotangentHCotan(x) = (Exp(x) + Exp(-x)) / (Exp(x) - Exp(-x))
Inverse Hyperbolic SineHArcsin(x) = Log(x + Sqr(x * x + 1))
Inverse Hyperbolic CosineHArccos(x) = Log(x + Sqr(x * x - 1))
Inverse Hyperbolic TangentHArctan(x) = Log((1 + x) / (1 - x)) / 2
Inverse Hyperbolic SecantHArcsec(x) = Log((Sqr(-x * x + 1) + 1) / x)
Inverse Hyperbolic CosecantHArccosec(x) = Log((Sgn(x) * Sqr(x * x + 1) + 1) / x)
Inverse Hyperbolic CotangentHArccotan(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:

PublicConstPiAsDouble=3.14159265358979PublicFunctionAtan2(ByValyAsDouble,ByValxAsDouble)AsDoubleIfy>0ThenIfx>=yThenAtan2=Atn(y/x)ElseIfx<=-yThenAtan2=Atn(y/x)+PiElseAtan2=Pi/2-Atn(x/y)EndIfElseIfx>=-yThenAtan2=Atn(y/x)ElseIfx<=yThenAtan2=Atn(y/x)-PiElseAtan2=-Atn(x/y)-Pi/2EndIfEndIfEndFunction

Other functions:

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


Previous: Getting StartedContentsNext: Branching
Retrieved from "https://en.wikibooks.org/w/index.php?title=Visual_Basic/Simple_Arithmetic&oldid=3676439"
Category:

[8]ページ先頭

©2009-2025 Movatter.jp