165 views

Uploaded by api-3738474

- Error_SPS25_note_1864952
- Reading Data From Keyboard Using DataInputStream BufferedReader and Scanner
- operating system and compiler lab manual
- Bronie Str
- TextMarker user guide
- coursefile 1
- dfgBook
- Xtreams - Michael Lucas-Smith and Martin Kobetic
- os&cd
- Compiler Design Pur Vi
- Compiler Desing-final ppt2.pptx
- Yacc
- os&cd
- compiler_lex
- jlex
- 12mgu Btech2010 It
- 13
- mpp(1)
- Determining Task Optimal Modular Robot Assembly Configurations
- ECE- 301

You are on page 1of 8

In addition to performing simple arithmetic and string operations with the arithmetic and

string operators, Visual Basic programs can take advantage of several built-in

mathematical functions and string functions to perform useful processing that,

otherwise, could require highly complex original code.

Mathematical Functions

Popular mathematical functions are summarized in the following table. Note that certain

functions do not require the Math. prefix.

Function Use

Returns the absolute value.

Math.Abs()

Math.Abs(-10) returns 10.

Returns an integer that is greater than or equal to a number.

Math.Ceiling()

Math.Ceiling(5.333) returns 6.

Returns the integer portion of a number.

Fix()

Fix(5.3333) returns 5.

Returns an integer that is less than or equal to a number.

Math.Floor()

Fix(5.3333) returns 5.

Returns the integer portion of a number.

Int()

Int(5.3333) returns 5.

Returns the larger of two numbers.

Math.Max()

Math.Max(5,7) returns 7.

Returns the smaller of two numbers.

Math.Min()

Math.Min(5,7) returns 5.

Returns a number raised to a power.

Math.Pow()

Math.Pow(12,2) returns 144.

Returns a random number between 0 and 1. Used in conjunction with

Rnd()

Randomizestatement to initialize the random number generator.

Rounds a number to a specified number of decimal places. Rounds up on

Math.Round() .5.

Math.Round(1.1234567,5) returns 1.12346.

Returns the sign of a number. Returns -1 if negative and 1 if positive.

Math.Sign()

Math.Sign(-5) returns -1.

Returns the square root of a positive number.

Math.Sqrt()

Math.Sqrt(144) returns 12.

Random Numbers

The Rnd() function returns a random number between 0 and 1. More likely, the need is to

generate a number within a particular range, between a given low and high number. This

is accomplished with the following formula.

For instance, to generate a random number between 0 and 10 the formula becomes

Math.floor((10 - 0 + 1) * Rnd() + 0)

String Functions

concatenation with the "&" operator. These functions are summarized in the following

table.

Function Use

Returns the character code of the first character of a string.

Asc()

Asc("A") returns 65.

Returns the display character of a character code.

Chr()

Chr(65) returns "A".

Returns the character at a specified position in a string, counting from 1.

GetChar()

GetChar("This is a string", 7) returns "s".

Returns the starting position in a string of a substring, counting from 1.

InStr()

InStr("This is a string", "string") returns 11.

Returns the starting position in a string of a substring, searching from the

InStrRev() end of the string.

InStr("This is a string", "string") returns 11.

Returns the lower-case conversion of a string.

LCase()

LCase("THIS IS A STRING") returns "this is a string".

Returns the left-most specified number of characters of a string.

Left()

Left("This is a string", 4) returns "This".

Returns the length of a string.

Len()

Len("This is a string") returns 16.

Removes any leading spaces from a string.

LTrim()

LTrim(" This is a string") returns "This is a string".

Mid() Returns a substring from a string, specified as the starting position

(counting from 1) and the number of characters.

Mid("This is a string", 6, 4) returns "is a".

Replaces all occurences of a substring in a string.

Replace() Replace("This is a string", " s", " longer s") returns "This are a longer

string" (replaces an "s" preceded by a blank space).

Returns the right-most specified number of characters of a string.

Right()

Right("This is a string", 6) returns "string".

Removes any trailing spaces from a string.

RTrim()

RTrim("This is a string ") returns "This is a string".

Returns the string equivalent of a number.

Str()

Str(100) returns "100".

Fills a string with a given number of spaces.

Space()

"This" & Space(5) & "string" returns "This string".

Compares two strings. Return values are 0 (strings are equal), 1 (first string

has the greater value), or -1 (second string has the greater value) based on

StrComp()

sorting sequence.

StrComp("This is a string", "This string") returns -1.

Reverses the characters in a string.

StrReverse()

StrReverse("This is a string") returns "gnirts a si sihT".

Removes any leading and trailing spaces from a string.

Trim()

Trim(" This is a string ") returns "This is a string".

Returns the upper-case conversion of a string.

UCase()

UCase("This is a string") returns "THIS IS A STRING".

Converts a numeric expression to a number.

Val()

Val( (1 + 2 + 3)^2 ) returns 36.

The above summaries give you a basic idea of the uses of these arithmetic and string

functions. There are occasions throughout these tutorials to see them in action and in

combination as they are applied to various processing needs.

Introduction

My company needed a small expression evaluator to use in

our .NET application. Using the .NET framework compilation

capabilities seem to be the most obvious way to make an

evaluator. However, in practice this technique has a nasty

side effect, it looks like it creates a new DLL in memory

each time you evaluate your function and it seems nearly

impossible to unload the DLL. You can refer to remarks at

the end of the article Evaluating Mathematical Expressions

by Compiling C# Code at Runtime for more details.

compile VB source. On the contrary, it parses your

expression and evaluates its value.

can do the following:

to change the evaluator code.

The evaluator can be run with just two lines of code:

Dim res As integer = CInt(mEvaluator.Eval("1+1"))

evaluator

The evaluator raises an event GetVariable when a keyword is

not detected. There is no need for you to publish all the

variables and then run the eval. On the contrary, you can

provide an on demand function which provides only the

needed variables:

Private Sub Evaluator1_GetVariable(ByVal name As String, _

ByRef value As Object) Handles Evaluator1.GetVariable

Select Case name

Case "anumber"

value = 5.0

Case "theForm"

value = Me

Case "adate"

value = #1/1/2005#

End Select

End Sub

functions

The member functions found in the class EvalFunctions are

automatically used by the evaluator. In this example, you

can see how we can make the evaluator implement the sin and

now functions:

Function sin(ByVal v As Double) As Double

Return Math.Sin(v)

End Function

Return Microsoft.VisualBasic.Now

End Function

As you can see you don't need much wrapping, the function

can be written and used straightaway in this class. Note

however that the evaluator does not make any distinction

between the Integers and Doubles. Therefore, remember to use

Doubles and not Integers for your function parameters.

The evaluator is made of a classic Tokenizer followed by a

classic Parser. I wrote both of them in VB, without using

any Lex or Bisons tools. The aim was readability over

speed. Tokenizing, parsing and execution is done in one

pass. This is elegant and at the same time quite efficient

because the evaluator never looks ahead or back, more than

one character.

The tokenizer

It reads the characters one by one and changes its state

according to the characters it encounters. When it

recognizes one of the recognized Token types, it returns it

to the parser. If it does not recognize a character, it

will raise a syntax error exception.

Collapse

' Recognized token types :

Private Enum eTokenType

none ' temporary state

end_of_formula ' when the tokenizer reach the end

operator_plus ' +

operator_minus ' -

operator_mul ' *

operator_div ' /

operator_percent ' %

open_parenthesis ' (

comma ' ,

dot ' .

close_parenthesis ' )

operator_ne ' <>

operator_gt ' <=

operator_ge ' >=

operator_eq ' =

operator_le ' <=

operator_lt ' <

operator_and ' AND

operator_or ' OR

operator_not ' NOT

operator_concat ' &

value_identifier ' any word starting with a letter or _

value_true ' TRUE

value_false ' FALSE

value_number ' any number starting 0-9 or .

value_string ' any string starting ' or "

open_bracket ' [

close_bracket ' ]

End Enum

syntax. The evaluator is split into two classes, one does

the tokenization and the second processes the tokens. This

is the standard way of doing it. This is quite flexible

also. This way, if you wish you could amend it to accept a

C++ syntax by changing the way the parser detects the

operators eq, ne, and, or, not... Changing the Tokenizer

will not force you to reprogram the rest of the evaluator.

The Parser

is like the Tokenizer with a sort of flow machine, a bit

like a pipe. It will process the token one by one without

looking ahead or back.

parts and right parts. In the expression 1 + 2, I

call + the operator, 1 is the left part and 2 is

the right part.

priorities. For example, the expression:

1 + 2 * 3

1 * 2 + 3

The multiplication has more priority than addition.

Therefore:

1 + 2 * 3 = 1 + 6 = 7

1 * 2 + 3 = 2 + 3 = 5

none = 0

[concat] = 1

[or] = 2

[and] = 3

[not] = 4

equality = 5

plusminus = 6

muldiv = 7

percent = 8

unaryminus = 9

End Enum

call the parser to get the right part. When the parser

returns the right part, the operator can apply its

operation (for example +) and the parsing continues.

The interesting part is that while calculating the right

part, the Tokenizer already knows its current level of

priority. Therefore, while parsing the right part, if it

detects an operator with more priority, it will continue

its parsing and return only the resulting value.

Yes, the evaluator supports the . operator. If you enter the

expression theForm.text then the evaluator will return the

title of the form. If you enter the expression theForm.left,

it will return its runtime left position. This feature is

only experimental and has not been tested yet. That is why

I have put this code here, hoping others will find its

features valuable and submit their improvements.

evaluate the custom functions. And the same code is used to

access the object's methods and properties. When the parser

encounters an identifier that is a keyword without any

meaning for it, it will try to reflect the CurrentObject to

see if it can find a method or a property with the same

name.

mi = CurrentObject.GetType().GetMethod(func, _

_Reflection.BindingFlags.IgnoreCase _

Or Reflection.BindingFlags.Public _ Or

Reflection.BindingFlags.Instance)

parameters.

valueleft = mi.Invoke(CurrentObject, _

_ System.Reflection.BindingFlags.Default, Nothing,

_ DirectCast(parameters.ToArray(GetType(Object)), Object()), Nothing)

- Error_SPS25_note_1864952Uploaded byRu Bén
- Reading Data From Keyboard Using DataInputStream BufferedReader and ScannerUploaded byAniket Mallick
- operating system and compiler lab manualUploaded bysaranyakarthik
- Bronie StrUploaded byabdel_lak
- TextMarker user guideUploaded byDmitry Dontsov
- coursefile 1Uploaded byanjaniit12
- dfgBookUploaded bySauravSachidanand
- Xtreams - Michael Lucas-Smith and Martin KobeticUploaded bySmalltalk Solutions
- os&cdUploaded bymanikanta89
- Compiler Design Pur ViUploaded byPurvi Majoka
- Compiler Desing-final ppt2.pptxUploaded byTanya Singhal
- YaccUploaded bySuraj Mysore
- os&cdUploaded byammusctce
- compiler_lexUploaded byHarsh
- jlexUploaded byZozor Dedos
- 12mgu Btech2010 ItUploaded byjayakrrishnan
- 13Uploaded byYoann Dragneel
- mpp(1)Uploaded byDestinifyd Mydestiny
- Determining Task Optimal Modular Robot Assembly ConfigurationsUploaded bywanghechen0076174
- ECE- 301Uploaded byviraniyan
- BookUploaded byBartStuck
- Compsci CheersUploaded bycurttremblay
- Clustering With Multiviewpoint-BasedUploaded bySuveetha Suvi
- 10.1.1.60Uploaded byyhavhe
- String BufferUploaded bySourabh Bhandari
- Forging High-Quality User Stories.pdfUploaded byKiv Soreangsey
- Java Interview Programs 3Uploaded byprathap7475
- FALLSEM2018-19_CSE1001_LO_SMVG16_VL2018191001940_Reference Material IV_C Program on String.docxUploaded byMeghna Biswas
- Set3Uploaded byAA
- MATLABUploaded byJonathan Farias

- .Netlecture DatabaseUploaded byapi-3738474
- Convert Number to Text JavaUploaded byapi-3738474
- FramesUploaded byapi-3738474
- Schema ni jm saUploaded byapi-3738474
- Database 2Uploaded byapi-3738474
- Schema ni jm saUploaded byapi-3738474
- VP Exercise 3 Part 3Uploaded byapi-3738474
- Flash, LectureUploaded byapi-3738474
- kamikutoUploaded byapi-3738474
- WhileUploaded byapi-3738474
- Push Down AutomataUploaded byapi-3738474
- JAVA ProjectUploaded byapi-3738474
- JAVA ProjectUploaded byapi-3738474
- FriendsterUploaded byapi-3738474
- REPORT AutomataUploaded byapi-3738474
- Adobe Photoshop Tutorials 5Uploaded byapi-3738474
- VP Exercise 3Uploaded byapi-3738474
- History of Unix and JavaUploaded byapi-3738474
- Adobe Photoshop Tutorial 3Uploaded byapi-3738474
- VP Exercise 1Uploaded byapi-3738474
- Lessons (Jazz)Uploaded byapi-3738474
- HTML NotesUploaded byapi-3738474
- Delos Reyes Jose Mari Luis CUploaded byapi-3738474
- 6738884 Adobe Photoshop Tutorial 2Uploaded byrania_elias
- VP Exercise 3 Part 2Uploaded byapi-3738474
- Adobe Photoshop Tutorial 4Uploaded byAneel Byanjankar
- 6738877 Adobe Photoshop Tutorial 1Uploaded byrania_elias
- Exercise 2 ArraysUploaded byapi-3738474
- HTML Notes and CodesUploaded byapi-3738474

- WB 1858 CME Framing Price MovementUploaded byjanos_torok_4
- Hum Drum ScoreUploaded byJulian Eduardo Garcia Peña
- Tip-of-the-tongue States_ Phenomenology, Mechanism, and Lexical RetrievalUploaded byJo Jo
- Army Transformation a View From the u.s. Army War College Pub256Uploaded byscparco
- EHT Application NoteUploaded byJuan Sanchez
- Development of Performance Models and Maintenance Standars of Urban Pavements for Network Management, Aleli Osorio 2015Uploaded byperezjoseorellana
- ThirdyrbscitsyallabusUploaded bymth34
- Oracle Applications R12 - HRMS and Payroll - V3Uploaded bylaiq
- Isozaki Arata - MA - The Japanese Sense of Place.pdfUploaded byVictor Hugo Dantas
- 99-T038Uploaded byGowthamraj
- Advanced Electronic Vaulting SolutionsUploaded bymboucher
- Google Adwords Display Exam by AdCertsUploaded byAdCerts
- Course Outline EntrepreneurshipUploaded bySaad Niazi
- SWARNREKHA A1.pdfUploaded byankit
- No GpsUploaded byluisignacioalonzo
- Atom e6xx Series DatasheetUploaded byKishore DM
- 2008 Fall Dr NewsletterUploaded byWileyProtocol
- linear algebra in a nutshellUploaded byDocFunkenstein
- Plasma LG - EngUploaded bymenetz
- Service Culture - Managers Communication Kit - August 2016_FinalUploaded byEnrique Sotelo Rangel
- UFD3UX (3)Uploaded byfirdakusumaputri
- Research Proposal[1]Uploaded byWaheed Rehman
- Kumpulan kumpulan Contoh Makalah Teknik Mesin Sample Paper lengkapUploaded byandino yoga
- 1 Tutorial Rolling Contact BearingUploaded byNirav
- METROHM ASTM D 8045 nou_AN-h141.pdfUploaded byCorina Stanculescu
- OAUGPresentation012910.pptxUploaded byrpillz
- Tesis EgiptoUploaded byJohnJosePartidas
- WacUploaded bykriteesinha
- Impact of Recession on Cement IndustryUploaded byVikas Yadav
- mccain1991.pdfUploaded byMrbughyo