MathHandbook.com

Computer Algebra System with Learning

 

 

Dr. Weiguang HUANG

 

226 Anzac Pde, Kensington, Sydney, NSW 2033, Australia

Phone:  +61 (0) 413008019

E-mail: DrHuang@DrHuang.com

www.DrHuang.com

 

 

8/5/2015

 

 

Copyright (C) 1990-2015

 

 


Contents

 

PART 1  User's Guide............................................. 7

1.         Introduction..................................................... 7

1.1.         What is SymbMath......................................... 7

1.2.     Capabilities..................................................... 7

1.3.  Shareware and Advanced Versions.................... 8

1.4  A List of Files in SymbMath................................. 8

2. Calculation......................................................... 10

2.1. Exact Calculation.............................................. 10

2.2.   Discontinuity and One-sided Value.................. 11

2.3.  Undefined and Indeterminate Form................... 11

3. Simplification..................................................... 12

3.1. Assuming Domain............................................. 13

3.2. Comparing and Testing Numbers...................... 14

4.   Defining Functions, Procedures and Rules 15

4.1.    Defining Functions......................................... 15

4.1.1.  Defining Conditional Functions................................................. 16

4.1.2.  Defining Case Functions.......................................................... 16

4.1.3.  Defining Piece-wise Functions................................................. 16

4.1.4.  Defining Recursion Functions.................................................. 17

4.1.5.  Defining Multi-Value Functions................................................. 17

4.2.  Defining Procedures......................................... 17

4.3.  Defining Rules................................................. 18

5.    Limits............................................................... 18

5.1.  One-sided Limits.............................................. 18

5.2.  Numeric Limits: nlim()...................................... 20

6. Differentiation.................................................... 20

6.1.  Fractional Derivatives....................................... 21

6.2.  Defining f (x).................................................... 21

7.  Integration......................................................... 22

7.1. Indefinite Integration.......................................... 22

7.2. Definite Integration............................................ 24

7.3.  Numeric Integration.......................................... 24

8.    Solving Equations.......................................... 25

8.1. Solving Algebraic Equations.............................. 25

8.2.  Equation Solver: solve()................................... 26

8.3.  Polynomial Solver: psolve().............................. 27

8.4.  Numeric Solver: nsolve().................................. 27

8.5.  Solving Differential Equations........................... 27

8.6.  Differential Solver: dsolve().............................. 28

9.  Sums, Products, and Series........................... 28

9.1.  Partial Sum...................................................... 29

9.2.  Indefinite Sum.................................................. 29

9.3.  Series.............................................................. 29

9.4.  Polynomials..................................................... 30

10.          Lists and Arrays, Vectors and Matrices.. 31

10.1.    Lists............................................................. 31

10.1.1.  Entering Lists........................................................................ 31

10.1.2.     Accessing Lists.................................................................. 31

10.1.3.     Modifying Lists................................................................... 32

10.1.4.     Operating Lists.................................................................. 32

10.2.    Arrays.......................................................... 34

10.2.1.  Entering Arrays..................................................................... 34

10.2.2.  Accessing Arrays.................................................................. 34

10.2.3.  Modifying Arrays................................................................... 34

10.2.4.  Operating Arrays.................................................................. 34

10.3.     Vectors and Matrices.................................. 35

11.    Statistics....................................................... 35

12.     Tables of Function Values......................... 35

13.   Conversion.................................................... 36

13.1.  Converting to Numbers.................................. 36

13.2.  Converting to Lists......................................... 36

13.3.  Converting to Strings...................................... 37

13.4.  Converting to Table........................................ 37

14.    Getting Parts of Expression....................... 37

14.1.  Getting Type of Data...................................... 37

14.2.  Getting Operators........................................... 37

14.3.  Getting Operands........................................... 38

14.4.  Getting Coefficients........................................ 38

15.    Database....................................................... 38

15.1.  Phone Number............................................... 39

15.2.  Atomic Weight................................................ 39

15.3.  Chemical Reaction......................................... 39

16.  Learning from User........................................ 39

16.1.  Learning Integrals from a Derivative............... 39

16.2.  Learning Complicated Integrals from a Simple Integral............................................................................... 41

16.3.  Learning Definite Integral from Indefinite Integral 42

16.4. Learning Complicated Derivatives from Simple Derivative................................................................ 42

16.5.  Learning Integration from Algebra................... 42

16.6.  Learning Complicated Algebra from Simple Algebra............................................................................... 42

16.7.  Learning vs. Programming.............................. 43

PART 2    Programmer's Guide........................... 44

17.  Programming in SymbMath.......................... 44

17.1.  Data Types.................................................... 44

17.1.1.  Numbers.............................................................................. 44

17.1.2.  Constants............................................................................. 45

17.1.3.  Variables.............................................................................. 46

17.1.4.  Patterns............................................................................... 47

17.1.5.  Functions, Procedures and Rules........................................... 47

17.1.5.1.  Standard Mathematical Functions....................................... 47

17.1.5.2.  Calculus Functions............................................................. 48

17.1.5.3.  Test Functions................................................................... 49

17.1.5.4.  Miscellaneous Functions..................................................... 51

17.1.5.5.     User-defined Functions.................................................... 52

17.1.5.6.  Procedures........................................................................ 52

17.1.5.7.  Rules................................................................................. 52

17.1.6.  Equations............................................................................. 52

17.1.7.  Inequalities........................................................................... 53

17.1.8.  Vectors or Lists..................................................................... 53

17.1.9.  Matrices or Arrays................................................................ 53

17.1.10.  Strings................................................................................ 53

17.2.   Expressions.................................................. 54

17.2.1.   Operators............................................................................ 54

17.2.1.1.  Arithmetic Operators.......................................................... 55

17.2.1.2.  Relational Operators.......................................................... 55

17.2.1.3.    Logical Operators............................................................. 55

17.2.2.  Function Calls....................................................................... 56

17.3.    Statements.................................................. 56

17.3.1.  Comment Statements........................................................... 56

17.3.2.  Evaluation Statements.......................................................... 57

17.3.3.  Assignment Statements........................................................ 57

17.3.4.  Conditional........................................................................... 58

17.3.5.  Loop.................................................................................... 58

17.3.6.  Switch.................................................................................. 59

17.3.6.1.  Output Switch.................................................................... 59

17.3.6.2.  Case Switch....................................................................... 59

17.3.6.3.  Numeric Switch.................................................................. 59

17.3.6.4.  Expand Switch................................................................... 60

17.3.6.5.  ExpandExp Switch............................................................. 60

17.3.7.  Read and Write Statements................................................... 60

17.3.8.  DOS Command.................................................................... 61

17.3.9.  Sequence Statements........................................................... 61

17.4.  Libraries and Packages.................................. 61

17.4.1.  Initial Package init.sm............................................................ 63

17.4.2.  ExpandLn Package............................................................... 63

17.4.3.  Chemical Calculation Package............................................... 63

17.5.  Interface with Other Software................................................... 64

18.   Graphics......................................................... 64

18.1.  Drawing Lines and Arcs.................................. 65

18.2.  Plotting f(x).................................................... 66

18.3.  Plotting Parametric Functions x(t) and y(t)...... 67

18.4.    Plotting f(t) in Polar Coordinates................... 67

18.5.  Plotting Data.................................................. 68

18.6.     Printing Graphics on Printer........................... 68

Part 3 Reference Guide........................................ 69

19.  SymbMath Environment: Windows and Menus................................................................................. 69

19.1.  File Menu....................................................... 69

19.1.1.  Open.................................................................................... 70

19.1.2.  New..................................................................................... 70

19.1.3.  Save Input............................................................................ 70

19.1.4.  Save Output......................................................................... 70

19.1.5.  DOS Shell............................................................................ 70

19.1.6.  Exit...................................................................................... 70

19.2.  Input Menu..................................................... 71

19.3.  Run Menu...................................................... 71

19.4.  Output Menu.................................................. 71

19.5.  Color Menu.................................................... 71

19.5.1.  Menu Line............................................................................ 71

19.5.2.  Input Window........................................................................ 71

19.5.3.  Input Border......................................................................... 72

19.5.4.  Output Window..................................................................... 72

19.5.5.  Output Border....................................................................... 72

19.5.6.  Status Line........................................................................... 72

19.6.  Help Menu..................................................... 72

19.7.  Example Menu............................................... 73

19.8.  Keyword Menu............................................... 73

19.9.  Editor and Edit Help Menu.............................. 73

19.9.1.  Edit Help Menu..................................................................... 73

19.9.1.1.  Show Help File................................................................... 74

19.9.1.2.  Cursor Movement Commands............................................ 74

19.9.1.3.  Insert and Delete Commands............................................. 74

19.9.1.4.  Search and Replace Commands......................................... 75

19.9.1.5.  Block Commands............................................................... 75

19.9.1.6.  Special Block Commands................................................... 77

19.9.1.9.  Miscellaneous Commands.................................................. 77

19.9.1.10.   Global Commands........................................................... 78

19.9.2.  Edit Commands.................................................................... 78

19.9.3. Copy and Paste..................................................................... 81

20.   Inside SymbMath........................................... 83

20.1.  Internal Structure........................................... 83

20.2.  Internal Format.............................................. 84

21. System Limits.................................................. 84

22. Keywords......................................................... 85

22.1.     Internal Functions....................................... 85

22.2.     External Functions...................................... 85

22.3.    Keywords in Alphabetical Order.................... 86

22.4.     Keywords in Topic Order............................. 87

22.5.     Glossary..................................................... 93

 


PART 1  User's Guide

 

1.   Introduction

1.1. What is SymbMath

 

            SymbMath (an abbreviation for Symbolic Mathematics) is a symbolic calculator that can solve symbolic math problems.

            SymbMath is a computer algebra system that can perform exact, numeric, symbolic and graphic computation. It manipulates complicated formulas and returns answers in terms of symbols, formulas, exact numbers, tables and graph.

            SymbMath is an expert system that is able to learn from user's input. If the user only input one formula without writing any code, it will automatically learn many problems related to this formula (e.g. it learns many integrals involving an unknown function f(x) from one derivative f’).

           SymbMath is a symbolic, numeric and graphics computing environment where you can set up, run and document your calculation, draw your graph.

SymbMath uses external functions as if standard functions since the external functions in library are auto-loaded.

            SymbMath is a programming language in which you can define conditional, case, piecewise, recursive, multi-value functions and procedures, derivatives, integrals and rules.

            SymbMath is database where you can search your data.

            It runs on IBM PCs (8086) with 400 KB free memory under MS-DOS.

 

 

1.2.     Capabilities

 

            It can provide analytical and numeric answers for:

            *  Differentiation: regular or higher order, partial or total, mixed and implicit differentiation, one-sided derivatives.

            *  Integration: indefinite or definite integration, multiple integration, infinity as a bound, parametric or iterated implicit integration.

            *  Solution of equations: roots of a polynomial, systems of algebraic or differential equations.

            *  Manipulation of expressions: simplification, factoring or expansion, substitution, evaluation.

            *  Calculation: exact and floating-point numeric computation of integer, rational, real and complex numbers in the range from minus to plus infinity, even with different units.

            *  Limits: real, complex or one-sided limits, indeterminate forms.

            *  Complex: calculation, functions, derivatives, integration.

            *  Sum and product: partial, finite or infinite.

            *  Others: series, lists, arrays, vectors, matrices, tables, etc.

           

Also included are:

            *  External functions in library as if standard functions.

            *  Plot: functions, polar, parametric, data, and list.

            *  Draw: lines, arcs, ellipse, circles, ovals.

            * Procedural, conditional, iteration, recursive, functional, rule-based, logic, pattern-matching and graphic programming.

            *  Searching database.

 

1.3.  Shareware and Advanced Versions

 

            You should register with the author if you use SymbMath.

            Please read all * files before running SymbMath. Please copy-and-past examples in the Help window to practise. The printed documents (100+ pages) is available from author.

            If you get the SymbMath on ZIP format (e.g. sm32a.zip), you should unzip it with parameter -d by

                        pkunzip -d sm32a c:\symbmath

            If you get the SymbMath with the install file, you should install it by                                            install

            On the MS-DOS prompt to run it, type               SymbMath

            SymbMath has two versions: Shareware Version A, and Advanced Version C. The Shareware version lacks the solve(), trig (except sin(x) and cos(x)), and hyperbolic functions, (lack 10% keywords). You cannot input these lack functions in Shareware version.

 

------------------------------------------------------------------------------------------

Version             Class   Lacked functions                                  

 

Shareware        A          solve(), hyperbolic,                              

                                    trig (except sin(x), cos(x))

Advanced         C                                                                     

Libraries           * . li                                                     

Manual             printed                                     

...........................................................................................................................

Upgrade           same                                                   

...........................................................................................................................

Multiple            copies  >2                                                                   

...........................................................................................................................

Site licence       >10 copies                                                       

------------------------------------------------------------------------------------------

 

            You must provide the photocopy of your license or license number for upgrades.

            If you send the author your payment by cheque, money order or bank draft that must be drawn in Australia, you will get the latest version. If you sign the license (see the LICENSE file) and send it to the author, you will be a legal user for upgrades. If you write a paper about this software on publication, you will get a free upgrade.

            Its two versions (Shareware and Advanced) are available from the author. The Shareware version is available from my web sites.

            The Advanced version is copy-protected, so you must insert the original SymbMath disk into drive A or B before you run SymbMath. By default, it is drive B. If you use drive A, please copy (or rename) the DRIVE.A file to the SYMBMATH.DRI file, or you edit drive(2) into drive(1) in the SYMBMATH.DRI file.

 

1.4  A List of Files in SymbMath

 

---------------------------------------------------------------------------------------------------------------

In directory SymbMath:

 

SymbMath.exe              executable SymbMath system.

SymbMath.ini                initial file.

SymbMath.h*                help files, * is numbers.

SymbMath.dri               indicate which drive the original SymbMath disk is inserted into

init.sm                          initial SymbMath program file.

*.sm                             packages (user SymbMath program files).

prolog.err                     prolog error message file.

 

In directory SymbMath\BGI:

 

*.bgi                             BGI graphics drives.

*.chr                             stroked fonts.

 

 

In directory SymbMath\library:

 

*                                   the auto loaded libraries (external functions).

 

 

In directory SymbMath\keyword:

 

*.key                            the keyword files.

 

In directory SymbMath\text:

 

SymbMath                    introduction of SymbMath.

readme             the read-me file, this file should be read first.

problem                        problems that other software cannot solve, but SymbMath can do.

comment*                     comments on SymbMath.

statisti              the download statistics at FTP site of garbo.uwasa.fi.

shareware                    Shareware concept.

software                       software available from the author.

update              the latest updates in SymbMath.

------------------------------------------------------------------------

 

 


2. Calculation

 

            In the following examples, a line of "IN: " means input, which you type in the Input window, then leave the Input window by pressing <Esc>, finally run the program by the command "Run"; while a line of "OUT: " means output. You will see both input and output are displayed on two lines with beginning of "IN: " and "OUT: " in the Output window. You should not type the word "IN: ". Some outputs may be omitted on the examples.

# is a comment statement.

            You can split a line of command into multi-lines of command by the comma ,. The comma without any blank space must be the last character in the line.

            Note that you should not be suprised if some functions in the following examples are not working when their libraries are not in the default directory or missing.

 

 

2.1. Exact Calculation

 

            SymbMath gives the exact value of calculation when the switch numeric := off (default), or the approximate value of numeric calculation when the switch numeric := on or by num().

            Mathematical functions are usually not evaluated until by num() or by setting numeric := on.

            SymbMath can manipulate units as well as numbers, be used as a symbolic calculator, and do exact computation. The range of real numbers is from -infinity to +infinity, e.g. ln(-inf), exp(inf+pi*i), etc. SymbMath contains many algorithms for performing numeric calculations. e.g. ln(-9), i^i, (-2.3)^(-3.2), 2^3^4^5^6^7^8^9, etc.

            Note that SymbMath usually gives a principle value if there are multi-values, but the solve() and root() give all values.

 

            Example:

            Exact and numeric calculations of 1/2 + 1/3.

IN:  1/2+1/3                  # exact calculation

OUT: 5/6

 

IN:  num(1/2+1/3)          # numeric calculation

OUT: 0.8333333333

 

            Evaluate the value of the function f(x) at x=x0 by f(x0).

 

            Example:

            Evaluate sin(x) when x=pi, x=180 degree, x=i.

IN:  sin(pi), sin(180*degree)

OUT: 0, 0

 

IN:  sin(i), num(sin(i))

OUT: sin(i), 1.175201 i

 

            Example:

            Set the units converter from the minute to the second, then calculate numbers with different units.

IN:  minute:=60*second

IN:  v:=2*meter/second

IN:  t:=2*minute

IN:  d0:=10*meter

IN:  v*t+d0

OUT: 250 meter

 

            Evaluate the expression value by

                        subs(y, x = x0)

 

            Example:

            Evaluate z=x^2 when x=3 and y=4.

IN:  z:=x^2                    # assign x^2 to z

IN:  subs(z, x = 3)         # evaluate z when x = 3

OUT: 9

 

IN:  x:=4                       # assign 4 to x

IN:  z                            # evaluate z

OUT: 16

 

            Note that after assignment of x by x:=4, x should be cleared from assignment by clear(x) before differentiation (or integration) of the function of x. Otherwise the x values still is 4 until new values assigned. If evaluating z by the subs(), the variable x is automatically cleared after evaluation, i.e. the variable x in subs() is local variable. The operation by assignment is global while the operation by internal function is local, but operation by external function is global. This rule also applies to other operations.

            The complex numbers, complex infinity, and most math functions with the complex argument can be calculated.

 

            Example .

IN:  sign(1+i), sign(-1-i), i^2

OUT: 1, -1, -1

 

            Example:

IN:  exp(inf+pi*i)

OUT: -inf

 

IN:  ln(last)

OUT: inf + pi*i

 

            The built-in constants (e.g. inf, zero, discont, undefined) can be used as numbers in calculation of expressions or functions.

 

 

2.2.   Discontinuity and One-sided Value

 

            Some math functions are discontinuous at x=x0, and only have one-sided function value. If the function f(x0) gives the discont as its function value, you can get its one-sided function value by f(x0-zero) or f(x0+zero).

 

            Example:

IN:  f(x_) := exp(1/x)                 # define function f(x)

IN:  f(0)

OUT: discont                            # discontinuity at x=0

 

IN:  f(0-zero)                             # left-sided value at x=0-

OUT: 0

 

IN:  f(0+zero)                            # right-sided value at x=0+

OUT: inf

 

 

2.3.  Undefined and Indeterminate Form

 

            If the function value is undefined, it may be indeterminate form (e.g. 0/0, inf/inf), you can evaluate it by lim() (see Chapter  Limits).

 

 

3. Simplification

 

            SymbMath automatically simplifies the output expression. You can further simplify it by using the built-in variable last in a single line again and again until you are happy with the answer.

            Expressions can be expanded by

                        expand(x)

                        expand := on

                        expandexp := on

            Remember that the operation by assignment is global while operation by function is local. So expand(x) only expands the expression x, but the switch expand := on expands all expressions between the switch expand := on and the switch expand := off. Second difference betwen them is that the switch expand := on only expands a*(b+c) and (b+c)/p, but does not expands the power (a+b)^2. The expandexp is exp expand.

 

            Example:

IN:  expand((a+b)^2+(b+c)*p)

OUT: a^2 + 2 a b + b^2 + b p + c p

 

IN:  expand := on

IN:  (a+b)^2 + (b+c)*p

OUT: (a+b)^2 + b p + c p

 

----------------------------------------------------------------------------------------

...............         expand(x) ..........................................

(a+b)^2             to         a^2+2*a*b+b^2

(a+b)^n             to         a^n+ ...... +b^n        n is positive integer

 

............... expand(x) and expand := on ..........................

a*(b+c)             to         a*b + a*c

(b+c)/p             to         b/p + c/p

 

............... expandexp := on .....................................

e^(a+b)             to           e^a *  e^b      

-----------------------------------------------------------------------------------------------

where a+b can be many terms or a-b.

 

            Expressions can be factorised by

                        factor(x)

            e.g.

IN:  factor(a^2 + 2*a*b + b^2)

OUT: (a + b)^2

 

            Polynomials of order less than 5 can be factorised by

                        factor(y, x)

 

            Example:

IN:  factor(x^2+5*x+6, x)

OUT: (2 + x) (3 + x)

 

            Example:

            Reduce sqrt(x^2).

IN:  sqrt(x^2)

OUT: x*sign(x)

 

            This output can be further simplified if you know properties of x.

            A first way is to evaluate x*sign(x) by substituting sign(x) with 1 if x is positive.

 

IN:  sqrt(x^2)

OUT: x*sign(x)

 

IN:  subs(last, sign(x) = 1)

OUT: x

 

where a special keyword last stands for the last output, e.g. here last is x*sign(x).

 

                       

3.1. Assuming Domain

 

            A second way is to assume x>0 before evaluation. If you assume the variable x is positive or negative, the output expression is simpler than that if you do not declare it.

 

IN:  assume(x > 0, y <0)             # assume x > 0, y < 0

OUT: assumed

 

IN:  sqrt(x^2), sqrt(y^2), sqrt(z^2)

OUT: x*sign(x), y*sign(y), z*sign(z)

 

IN:  last                            # simplify last output

OUT: x, -y, z*sign(z)

 

            In this way, all of x is affected until the assume() is cleared by clear(). The first method is local simplification, but the second method is global simplification.

            By default, |x| < inf and all variables are complex, except that variables in inequalities are real, as usual only real numbers can be compared. e.g. x is complex in sin(x), but y is real in y > 1.

           

            Table 3.1       Assuming

--------------------------------------------------------------------------------------------------------

Assume                        Assignment                  Meaning               

 

assume(x>y)                x>y := 1                                    # assume x > y

assume(x>=y)              x>=y := 1                      # assume x >= y

assume(x<y)                x<y := 1                                    # assume x < y

assume(x<=y)              x<=y := 1                      # assume x <= y

assume(x==y)              x==y := 1                      # assume x == y

assume(x<>y)              x<>y := 1                      # assume x <> y

                                    iseven(b) := 1               # assume b is even

                                    isodd(b) := 1                 # assume b is odd

                                    isinteger(b) := 1                        # assume b is integer

                                    isratio(b) := 1                # assume b is ratio

                                    isreal(b) := 1                 # assume b is real

                                    iscomplex(b) := 1          # assume b is complex

                                    isnumber(b) := 1           # assume b is number

                                    islist(b) := 1                  # assume b is a list

                                    isfree(y,x) := 1              # assume y is free of x

                                    issame(a,b) := 1           # assume a is same as b

                                    sign(b) := 1                   # assume b is positive complex

                                    sign(b) := -1                 # assume b is negative complex

------------------------------------------------------------------------------------------------------------

 

            The assume() can be cleared by clear(). e.g. clear(x>y).

            You can restrict the domain of a variable by assuming the variable is even, odd, integer, real number, positive or negative.

 

            Example:

 

IN:  isreal(b) := 1          # assume b is real

IN:  sqrt(b^2)

OUT: abs(b)

 

 

            Table 3.3          Simplification in different domains

----------------------------------------------------------------------------------

expression        complex           real                  x > 0

 

sqrt(x^2)          x sign(x)           |x|                     x

x*sign(x)          x sign(x)           |x|                     x

|x|*sign(x)         |x| sign(x)         x                      x

|x|/x                  |x|/x                  1/sign(x)           1

x+inf                 x+inf                 inf

x-inf                 x-inf                 -inf

abs'(x)              |x|/x                  1/sign(x)           1

-------------------------------------------------------------------------------------

 

 

3.2. Comparing and Testing Numbers

 

            You can compare two numbers by relational operators:

                        a > b

                        a < b

                        a <= b

                        a >= b

                        a <> b

                        a == b

 

            Example:

IN:  2 > 1, 2 < 1

OUT: 1, 0

 

            You also can compare two numbers, even complex numbers z1 and z2 by

                        islarger(z1, z2)

                        isless(z1, z2)

                        issame(z1, z2)

 

            Example:

            compare 1+i and 1-i.

IN:  islarger(1+i, 1-i)         # is 1+i larger than 1-i ?

OUT: 1                             # yes, 1+i > 1-i

 

            You can compare square of a variable a^2 > 0 if you know the property of the variable.

            Example:   

IN:  assume(a > 0)

IN:  a^2 > 0, 1/a > 0

OUT: 1, 1

 

            You can test if x is even, odd, integer, real, number or list by the functions:

                        iseven(x)

                        isodd(x)

                        isinteger(x)

                        isreal(x)

                        isnumber(x)

                        islist(x)

                        isfree(y,x)

                        islarger(a,b)

                        isless(a,b)

                        issame(a,b)

 

            Example:

IN:  iseven(2)                # is 2 even ?

OUT: 1                         # yes

 

            Note that comparison by the is* functions return either 1 if it is true or 0 otherwise, but comparison by relational operators gives 1 if it is true, 0 if it is fault, or left unevaluated otherwise.

 

 

4.   Defining Functions, Procedures and Rules

 

            Anytime when you find yourself using the same expression over and over, you should turn it into a function. 

            Anytime when you find yourself using the same definition over and over, you should turn it into a library.

            You can make your defined function as if the built-in function, by saving your definition into disk file as a library with the function name plus extension  as the filename. e.g. saving the factoria function as the factoria file (see Section Libraries and Packages).

 

 

4.1.    Defining Functions

 

            You can define your own functions by

                           f(x_) := x^2

            Here are some sample function definitions:

                           f(x_) := cos(x + pi/3)

                           g(x_, y_) := x^2 - y^2

            The argument in the definition should be the pattern x_. Otherwise f() works only for a specific symbolic value, e.g. x when defining f(x):=x^2. The pattern x_ should be only on the left side of the assignment.

            Once defined, functions can be used in expressions or in other function definitions:

                        y := f(3.2)

                        z := g(4.1, -5.3)

 

            Example:

Define a new function for x^2, then evaluate it.

           

IN:  g(x) := x^2

IN:  g(2), g(a),  g(x)

OUT: g(2), g(a),  x^2                # work only for a symbolic value x

 

IN:  f(x_) := x^2

IN:  f(2), f(a)

OUT: 4, a^2                              # work for any value

 

 

4.1.1.  Defining Conditional Functions

 

            You can define a conditional function by the If() function:

                        f1(x_) := If(x>0 ,   1)

                        f2(x_) := If(x>0 ,  x^2 ,  x)

or by inequalities:

                        f3(x_) := x>0

                        f4(x_) := (x>0) * x^2 + (x<=0) * x

            On the first definition by If(), when f1() is called it gives 1 if x>0, or left unevaluated otherwise. On the second definition by the If(), when f2() is called it gives x^2 if x>0, x if x<=0, or left unevaluated otherwise. On the third definition by the inequality, when f3() is called, it gives 1 for x>0, 0 for x<=0, or x>0 for symbolic value of x. On the last definition, when f4() is called, it is evaluated for any numeric or symbolic value of x.

            You cannot differentiate nor integrate the conditional function defined by If(), but you can do the conditional functions defined by inequalities.

 

            You can define a function evaluated only for numbers by

                        f(x_) := If(isnumber(x) ,  x^2)

            This definition is different from the definition by f(x_) := x^2. On the latter, when f() is called, it gives x^2, regardless whatever x is. On the former, when f() is called, it gives x^2 if x is a number, or left unevaluated otherwise.

           

            Example:

evaluate to x^2 only if x is number, by defining a conditional function.

 

IN:  f(x_) := If(isnumber(x) ,  x^2)

IN:  f(2), f(a)

OUT: 4, f(a)

 

IN:  f(x_) := If(x>0 ,  x^2)

IN:  f(2), f(-2), f(a)

OUT: 4, f(-2), f(a)

 

IN:  f(x_) := If(x>0 ,  x^2 ,  x)

IN:  f(2), f(-2), f(a)

OUT: 4, 2, f(a)

 

 

4.1.2.  Defining Case Functions

 

            You can define the case function by different pattern name. The case function is similar to the case statement in BASIC language.

            Example:

 

IN:  f(x_) := If( x > 0 and x < 1 ,  1)

IN:  f(u_) := If( u > 1 and u < 2 ,  2)

IN:  f(v_) := If( v > 2 and v < 3 ,  3)

IN:  f(0.2), f(1.2), f(2.2)

OUT: 1, 2, 3

 

 

4.1.3.  Defining Piece-wise Functions

 

            You can define a piece-wise function.

 

            Example:

            define

 

      / x              if x < 0

f(x) =  0                        if x = 0

      \ x^2           if x > 0

 

then evaluate f(-2), f(0), f(3), f(a), f’, d(f(x), x=3).

 

IN:  f(x_) := x*(x<0)+x^2*(x>0)

IN:  f(-2), f(0), f(3), f(a)

OUT: -2, 0, 9, (a < 0) a + (a > 0) a^2

 

IN:  f’

OUT: (x < 0) + 2 x (x > 0)

 

IN:  d(f(x), x=3)

OUT: 6

 

 

4.1.4.  Defining Recursion Functions

 

            You can define a recursion function.

            Example:

IN:  factoria(1) := 1

IN:  factoria(n_) := If(n > 1, (n-1)*factoria(n-1))

 

 

4.1.5.  Defining Multi-Value Functions

 

            You can define a function with the multi function values.

            Example:

IN:  squreroot(x_) := [sqrt(x), -sqrt(x)]

IN:  squreroot(4)

OUT: [2, -2]

 

 

4.2.  Defining Procedures

 

            You can define a function as a procedure by

                        f(x_) := block(command1, command2, ..., commandN)

                        f(x_) := block(command1, command2, ..., commandN, local(a))

 

            By default, all variables within procedure are global, except for variables declared by local(). The multi-statement should be grouped by block(). The block() only outputs the result of the last statement or the second last one as its value. The multi-line must be terminated by a comma, (not by a comma and a blank space). Local() must be the last one in block().

 

            Example:

define a numeric integration procedure ninte() and calculate integral of x^2 from x=1 to x=2 by call ninte().

 

IN:  ninte(y_,x_,a_,b_) := block( numeric:=on,

            dd:=(b-a)/50,

            aa:=a+dd,

            bb:=b-dd,

            y0:=subs(y, x = a),

            yn:=subs(y, x = b),

            (sum(y,x,aa,bb,dd)+(y0+yn)/2)*dd,

            local(dd,aa,bb,y0,yn) )

 

IN:  ninte(x^2, x, 1, 2)

 

 

4.3.  Defining Rules

 

            You can define transform rules. Defining rules is similar to defining functions. In defining functions, all arguments must be simple variables, but in defining rules, the first argument can be a complicated expression.

 

            Example:

            Define log rules.

IN:  log(x_ * y_) := log(x) + log(y)

IN:  log(x_ ^ n_) := n*log(x)

IN:  log(a*b)

OUT: log(a) + log(b)

 

            Example:

IN:  sin(-x_) := -sin(x)

IN:  sin(-a)

OUT: -sin(a)

 

            Example:

            Define derivatives (see Chapter 4.5.2 Defining f’).

IN:  f'(x_) := sin(x)

IN:  f'(t)

OUT: sin(t)

 

            Example:

            Define integrals (see Chapter 4.6.1 Indefinite Integration).

IN:  integrate(f(x_),x_) := sin(x)

IN:  integrate(f(t),t)

OUT: sin(t)

 

            Example:

            Define the trig simplification rules.

IN:  simplify(sin(x_)^2, x_) := 1/2*(1-cos(x))

IN:  simplify(sin(x)^2,x)

OUT: 1/2 (1 - cos(x))

 

            Example:

            Define Laplace transform rules.

IN:  laplace(sin(t_), t_) := 1/(t^2+1)

IN:  laplace(sin(s), s)

OUT: 1/(s^2 + 1)

 

 

5.    Limits 

5.1.  One-sided Limits

 

            You can finds real or complex limits, and discontinuity or one-sided value.

            First find the expression value by subs(y, x = x0) or the function value by f(x0) when x = x0.

            If the result is the discont (i.e. discontinuity), then use the one-sided value x0+zero or x0-zero to try to find the one-sided function or expression value.

            For a function f(x), you can evaluate the left- or right-sided function value, similar to evaluate the normal function value:      

                        f(x0-zero)

                        f(x0+zero)

            For an expression y, you can evaluate its one-sided expression value by

                        subs(y, x = x0-zero)

                        subs(y, x = x0+zero)

            The discont (discontinuity) means that the expression has a discontinuity and only has the one-sided value at x=x0. You should use x0+zero or x0-zero to find the one-sided value. The value of f(x0+zero) or f(x0-zero) is the right-sided or left-sided function value as approaching x0 from positive (+inf) or negative (-inf) direction, respectively, i.e. as x = x0+ or x = x0-.

            If the result is undefined (indeterminate forms, e.g. 0/0, inf/inf, 0*inf, and 0^0), then find its limit by

                        lim(y, x = x0)

            If the limit is discont, then you can find a left- or right-sided limit when x approaches to x0 from positive (+inf) or negative (-inf) direction at discontinuity by

 

                        lim(y, x = x0+zero)

                        lim(y, x = x0-zero)

 

            Example:

            Evaluate y=exp(1/x) at x=0, if the result is discontinuity, find its left-sided and right-sided values (i.e. when x approaches 0 from positive and negative directions).

 

IN:  y:=exp(1/x)

IN:  subs(y, x = 0)

OUT: discont               # discontinuity at x=0

 

IN:  subs(y, x = 0+zero), subs(y, x = 0-zero)

OUT: inf, 0

 

            Example:

            How to handle the following one-sided values ?

 

Let f(x) = 1 when x < 1, f(x) = 1 when x > 1 (and not defined at x = 1).

Let g(x) = 1 when x < 1, g(x) = 1 when x > 1, and g(1) = 2.

Let h(x) = 1 when x < 1, h(x) = 2 when x >= 1.

Let k(x) = 1 when x < 1, k(x) = 2 when x > 1, and k(1) = 3.

 

Now ask SymbMath to compute

 

(1) the limit as x approaches 1,

(2) the limit as x approaches 1 from the left, and

(3) the limit as x approaches 1 from the right

 

for each of the above piecewise defined functions.

 

# define functions

f(x_) :=  If(x<1 or x>1, 1)

f(1+zero):=1

f(1-zero):=1

g(x_) := If( x<1 or x>1, 1)

g(1):=2

g(1+zero):=1

g(1-zero):=1

h(x_) := If( x<1, 1, 2)

h(1+zero):=2

h(1-zero):=1

k(x_) := If( x<1, 1, If( x>1, 2))

k(1):=3

k(1+zero):=2

k(1-zero):=1

 

# evaluate functions

IN:  f(1), g(1), h(1), k(1)

OUT: f(1), 2, 2, 3

 

IN:  f(1+zero), g(1+zero), h(1+zero), k(1+zero)

# right-hand side value at x=1+

OUT: 1, 1, 1, 1

 

IN:  f(1-zero), g(1-zero), h(1-zero), k(1-zero)

# left-hand side value at x=1-

OUT: 1, 1, 2, 2

 

            Example:

Find limits of types 0/0 and inf/inf.

 

IN:  p:=(x^2-4)/(2*x-4)

IN:  subs(p, x = 2)

OUT: undefined

 

IN:  lim(p, x = 2)

OUT: 2

 

IN:  subs(p, x = inf)

OUT: undefined

 

IN:  lim(p, x = inf)

OUT: inf

 

 

5.2.  Numeric Limits: nlim()

 

            If symbolic limit falls, you should try numeric limit by

                        nlim(y, x=x0)

 

            e.g. nlim(sin(x)/x, x=0)

 

 

6. Differentiation

 

            Differentiate an expression y with respect to x by 

                        d(y, x)

            Differentiate a simple function f(x) with respect to x by

                        d(f(x))

            Differentiate y in the n order by

                        d(y, x, n)

            Differentiate y at x = x0 by

                        d(y, x = x0)

            Differentiate y at x = x0 in the n order by

                        d(y, x = x0, n)

            The order can be any number, e.g. 0.5 order is fractional derivative.

                       

            Example:

            Differentiate sin(x) and x^(x^x).

IN:  d(sin(x))    # it is the same as d(sin(x), x).

OUT: cos(x)

 

IN:  d(x^(x^x), x)

OUT: x^(x^x) (x^(-1 + x) + x^x ln(x) (1 + ln(x)))

 

            If you differentiate f(x) by f’, x must be a simple variable and f(x) must be unevaluated.

            f'(x0) is the same as d(f(x0),x0), but different from d(f(x), x=x0). f'(x0) first evaluates f(x0), then differentiates the result of f(x0). But d(f(x), x=x0) first differentiates f(x), then replace x with x0. Note that sin'(x^6) gives cos(x^6) as sin'(x^6) is the same as d(sin(x^6), x^6). sin'(0) gives d(0,0) as sin(0) is evaluated to 0 before differentiation, you should use d(sin(x),x=0) which gives 1.

 

            Example:

            Differentiate the expression f=sin(x^2+y^3)+cos(2*(x^2+y^3)) with respect to x, and with respect to both x and y.

IN:  f := sin(x^2+y^3)+cos(2*(x^2+y^3))

IN:  d(f, x)

OUT: 2 x cos(x^2 + y^3) - 4 x sin(2 (x^2 + y^3))

 

IN:  d(d(f, x), y)           # mixed derivative with x and y.

OUT: -6 x y^2 sin(x^2 + y^3) - 12 x y^2 cos(2 (x^2 + y^3))

 

6.1.  Fractional Derivatives

 

            Differentiate y at fractional order by

                        d(y, x , order)

                        d(y,x , -1.5)

 

            Example:

IN:  y:=d(sin(x), x, -1.5);

IN:   d(y, x,1.5)            

 

The Davison-Essex and the Riemann-Liouville definitions are different in the following aspect: in the D-E formula, differentiation is performed first, then integration; in the R-L formula it is the other way around. The D-E definition implemented, thus, maps constants to zero, imitating integer order differentiation, while the R-L definition does not. This property of the D-E definition makes it suitable to work with initial value problems for fractional differential equations.

 

6.2.  Defining f (x)

 

            Defining derivatives is similar to defining rules. You only need to define derivatives of a simple function, as SymbMath automatically apply the chain rule to its complicated function.

 

            Example:

IN:  f(x_) := sin(x);

IN:  f(x)

OUT: sin(x)

 

IN:  f(x^6)            # the same as d(f(x^6), x^6)

OUT: sin(x^6)

 

IN:  d(f(x^6), x)

OUT: 6 x^5 sin(x^6)

 

 

 

 

7.  Integration

 

            You can find integrals of x^m*e^(x^n), x^m*e^(-x^n), e^((a*x+b)^n), e^(-(a*x+b)^n), x^m*ln(x)^n, ln(a*x+b)^n, etc., (where m and n are any real number).

            It is recommended that before you do symbolic integration, you should simplify integrand, e.g. expand the integrand by expand() and/or by setting the switch expand:=on and/or expandexp:=on.

            If symbolic integration fails, you can define a simple integral and/or derivative, (or adding integral into the int library), then do integration again (see Chapter Learning From User).

 

 

7.1. Indefinite Integration

 

            Find the indefinite integrals of expr by

                        integrate(expr, x)

            Find the double indefinite integrals by

                        integrate(integrate(expr, x), y)

            Note that the arbitrary constant is not represented.

 

            Example:

            Find integrals of 1/a, 1/b and 1/x, knowing a >0, b is real.

 

IN:  assume(a>0), isreal(b):=1

IN:  integrate(1/a, a), integrate(1/b, b), integrate(1/x, x)

OUT: ln(a), ln(|b|), ln(x*sign(x))

 

            Example:

            Find indefinite integrals.

 

IN:  integrate(sin(a*x+b), x)        # integrands involving sin(x)

OUT: -cos(b + a x)/a

 

IN:  integrate( sin(x)/x^2, x)

OUT: ci(x) - sin(x)/x

 

IN:  integrate( x*sin(x), x)

OUT: -x cos(x) + sin(x)

 

IN:  integrate(sin(x)*cos(x), x)

OUT: (1/2)*sin(x)^2

 

IN:  integrate( e^(x^6), x)              # integrands involving e^x

OUT: 1/6 ei(-5/6, x^6)

 

IN:  integrate( x^2*e^x, x)

OUT: ei(2, x)

 

IN:  integrate( x*e^(-x), x)

OUT: -e^(-x) - x e^(-x)

 

IN:  integrate( e^x/sqrt(x), x)

OUT: ei(-0.5, x)

 

IN:  integrate(x^1.5*exp(x), x)

OUT: ei(1.5, x)

 

IN:  integrate(sin(x)*e^x, x)      # integrals involving sin(x) and e^x

OUT: 1/2 * (sin(x) - cos(x)) * e^x

 

IN:  integrate( x*ln(x), x)             # integrands involving ln(x)

OUT: -1/4 x^2 + 1/2 x^2 ln(x)

 

IN:  integrate( ln(x)^6, x)

OUT: li(6, x)

 

IN:  integrate( ln(x)/sqrt(x), x)

OUT: -4 sqrt(x) + 2 sqrt(x) ln(x)

 

IN:  integrate( ln(x)/sqrt(1 + x), x)

OUT: -4 sqrt(1 + x) + 2 sqrt(1 + x) ln(x) - 2 ln((-1 + sqrt(1 + x))/(1 + sqrt(1 + x)))

 

IN:  integrate( 1/(a x + b), x)                   # integrands involving polynomials

OUT: ln((b + a x) sign(b + a x))/a

 

IN:  integrate( x/(x^2 + 5 x + 6), x)

OUT: 1/2 ln(|6 + 5 x + x^2|) - 5/2 ln(|(2 + x)/(3 + x)|)

 

IN:  integrate( (x^3 + x)/(x^4 + 2 x^2 + 1), x)

OUT: 1/4 ln((1 + 2 x^2 + x^4) sign(1 + 2 x^2 + x^4))

 

            Example:

            Find the line integral.

 

IN:  x:=2*t

IN:  y:=3*t

IN:  z:=5*t

IN:  u:=x+y

IN:  v:=x-y

IN:  w:=x+y+z

IN:  integrate(u*d(u,t)+v*d(v,t)+w*d(w,t), t)

OUT: 63 t^2

 

            Example:

            Integrate x^2*e^x, then expand it by the mean of the packages "ExpandEi.sm" (expand ei(n,x)).  The packages "ExpandGa.sm" (expand gamma(n,x)) and "ExpandLi.sm" (expand li(n,x)) are similar one.

 

IN:  integrate(x^2*e^x, x)

OUT: ei(2,x)                                         # ei()

 

IN:  readfile("ExpandEi.sm")

IN:  ExpandEi(ei(2, x))

OUT: x^2 e^x - 2 x e^x + 2 e^x             # ei() is expanded

 

 

            Defining integrals is similar to defining rules.

            Example:

 

IN:  integrate(f(x_), x_) := sin(x)

IN:  integrate(f(t), t)

OUT: sin(t)

 

 

7.2. Definite Integration

 

            Find definite integrals by external functions

                        integrate(expr, x , xmin , xmax)

                        integrate(expr, x , xmin , singularity , xmax)

 

            Example:

            Find the definite integral of y=exp(1-x) with respect to x taken from 0 to infinity.

 

IN:  integrate(exp(1-x), x , 0 , inf)

OUT: e

 

            Example:

do discontinuous integration of 1/x^2 and 1/x^3 with discontinuity at x=0.

 

IN:  integrate(1/x^2, x , -1 , 2)               # singularity at x=0

OUT: inf

 

IN:  integrate(1/x^3, x , -1 , 1)               # singularity at x=0

OUT: 0

 

IN:  integrate(sqrt((x-1)^2), x , 0 , 2)      # singularity at x=1

OUT: 1

 

            SymbMath usually detect singularity, but sometime it cannot, in this case you must provide singularity.

 

            Example:

IN:  integrate(1/(x-1)^2, x , 0 , 1 , 2)      # provide singularity at x=1

OUT: inf

 

            Example:

            complex integration.

 

IN:  integrate(1/x, x , i , 2*i)

OUT: ln(2)

 

 

7.3.  Numeric Integration

 

            The external function

                        nint(y, x , xmin , xmax)

does numeric integration.

            Example:

Compare numeric and symbolic integrals of 4/(x^2+1) with respect to x taken from 0 to 1.

 

IN:  nint(4/(x^2+1), x , 0 , 1)

OUT: 3.1415

 

IN:  num(int(4/(x^2+1), x , 0 , 1))

OUT: 3.1416

 

 

8.    Solving Equations

8.1. Solving Algebraic Equations

 

            The equations can be operated (e.g. +, -, *, /, ^, expand(), d(), integrate()). The operation is done on both sides of the equation, as by hand. You can find roots of a polynomial, algebraic equations, systems of equations, differential and integral equations.

            You can get the left side of the equation by

                        left(left_side = right_side)

or get the right side by

                        right(left_side = right_side)

            You can assign equations to variables.

 

            Example:

 

IN:  eq1:= x + y = 3

IN:  eq2:= x - y = 1

IN:  eq1+eq2

OUT: 2 x = 4

 

IN:  last/2

OUT: x = 2

 

IN:  eq1-eq2

OUT: 2 y = 2

 

IN:  last/2

OUT: y = 1

 

            Example:

            Solve an equation sqrt(x+2*k) - sqrt(x-k) = sqrt(k), then check the solution by substituting the root into the equation.

 

IN:  eq1 := sqrt(x + 2*k) - sqrt(x - k) = sqrt(k)

OUT: eq1 := sqrt(x + 2*k) - sqrt(x - k) = sqrt(k)

 

IN:  eq1^2

OUT: ((2*k + x)^0.5 - ((-k) + x)^0.5)^2 = k

 

IN:  expand(last)

OUT: 2*x + k + (-2)*(2*k + x)^0.5*((-k) + x)^0.5 = k

 

IN:  last-k-2*x

OUT: (-2)*(2*k + x)^0.5*((-k) + x)^0.5 = (-2)*x

 

IN:  last/(-2)

OUT: (2*k + x)^0.5*((-k) + x)^0.5 = x

 

IN:  last^2

OUT: (2*k + x)*((-k) + x) = x^2

 

IN:  expand(last)

OUT: (-2)*k^2 + k*x + x^2 = x^2

 

IN:  last-x^2+2*k^2

OUT: k*x = 2*k^2

 

IN:  last/k

OUT: x = 2*k

 

IN:  subs(eq1, x = right(last))

OUT: k^0.5 = k^0.5

 

            You can solve algebraic equations step by step, as above. This method is useful in teaching, e.g. showing students how to solve equations.

 

 

8.2.  Equation Solver: solve()

 

            The solve() functions

 

                        solve(expr1 = expr2, x)

                        solve([expr1 = expr2, expr3 = expr4], [x, y])

 

solve a polynomial and systems of linear equations on one step. It is recommended to set the switch expand:=on when solve the complicated equations. All of the real and complex roots of the equation will be found by solve(). The function solve() outputs a list of roots when there are multi-roots. You can get one of roots from the list, (see Chapter 4.9 Arrays, Lists, Vectors and Matrices).

 

            Example:

            Solve a+b*x+x^2 = 0 for x, save the root to x.

 

IN:  solve(a+b*x+x^2 = 0, x)      # solve or re-arrange the equation for x

OUT: x = [-b/2 + sqrt((b/2)^2 - a),  -b/2 - sqrt((b/2)^2 - a)]

 

IN:  x := right(last)                                # assign two roots to x

OUT: x := [-b/2 + sqrt((b/2)^2 - a),  -b/2 - sqrt((b/2)^2 - a)]

 

IN:  x[1]                                                # the first root

OUT: -b/2 + sqrt((b/2)^2 - a)

IN:  x[2]                                                # the second root

OUT: -b/2 - sqrt((b/2)^2 - a)

 

            Example:

            Solve x^3 + x^2 + x + 5 = 2*x + 6.

 

IN:  num(solve(x^3+x^2+x+5 = 2*x+6, x))

OUT: x = [1, -1, -1]

 

            The function solve() not only solves for a simple variable x but also solves for an unknown function, e.g. ln(x).

 

            Example:

            Solve the equation for ln(x).

 

IN:  solve(ln(x)^2+5*ln(x) = -6, ln(x))

OUT: ln(x) = [-2, -3]

 

IN:  exp(last)

OUT: x = [exp(-2), exp(-3)]

 

            Example:

            Rearrange the equations.

 

IN:  eq := [x+y = 3+a+b, x-y = 1+a-b]                # assign equations to eq

IN:  solve(eq, [x,y])                                           # rearrange eq for x and y

OUT: [x = -1/2*(-4 - 2 a), y = -1/2*(-2 - 2 b)]

 

IN:  solve(eq, [a,b])                                           # rearrange eq for a and b

OUT: [a = -1/2*(4 - 2 x), b = -1/2*(2 - 2 y)]

 

IN:  solve(eq, [a,y])                                           # rearrange eq for a and y

OUT: [b = -1/2*(2 - 2 y), x = -1/2*(-4 - 2 a)]

 

IN:  solve(eq, [x,b])                                           # rearrange eq for x and b

OUT: [a = 1/2*(-4 + 2 x), y = 1/2*(2 + 2 b)]

 

 

8.3.  Polynomial Solver: psolve()

 

            The external function

                        psolve(f(x), x)

solves f(x)=0 for x. It is similar to solve(), but it only can solve polynomial with order < 3.

 

            e.g.

IN:  psolve(x^2+5*x+6, x)

OUT: [-2, -3]

 

 

8.4.  Numeric Solver: nsolve()

 

            The external functions

                        nsolve(f(x) = x, x)

                        nsolve(f(x) = x, x,x0)

numerically solves an algebraic equation with an initial value x0. By default x0=1. nsolve() only gives one solution near x0, omitting other solutions.

 

            Example:

IN:  nsolve( cos(x) = x, x)

OUT: x = 0.73911289091

 

IN:  nsolve( sin(x) = 0, x,0)                   # similar to asin( sin(x)=0 )

OUT: x = 0                                           # only gives one solution near x0=0

 

IN:  nsolve( sin(x) = 0, x,3)

OUT: x = 3.14                                       # only gives one solution near x0=3

 

 

8.5.  Solving Differential Equations

 

            You can solve the differential equations:

                        y' = f(x)

by integrating the equation.

            y'  is the same as d(y(x),x).

           

            Example:

            solve y'=sin(x) by integration.

IN:  integrate( y' = sin(x), x)

OUT: y(x) = constant - cos(x)

 

 

8.6.  Differential Solver: dsolve()

 

            The external function

                        dsolve(y'(x) = f(x,y), y(x), x)

can solve the first order variables separable and linear differential equations

                        y'(x) = h(x)

                        y'(x) = f(y(x))

                        y'(x) = f(y(x))*x

                        y'(x) = g(x)*y(x)

                        y'(x) = g(x)*y(x)+h(x)

on one step. Notice that y'(x) must be alone on the left hand side of the equation. It is recommended to set the switch expand:=on when solving the complicated differential equations.

 

            Example:

            Solve y'(x) = sin(x) by dsolve().

IN:  dsolve( y'(x) = sin(x), y(x), x)

OUT: y(x) = constant - cos(x)

 

            Example:

            Solve differential equations by dsolve(). If the result is a polynomial, then rearrange the equation by solve().

 

IN:  dsolve(y'(x) = x/(2+y(x)), y(x), x)

OUT: 2*y(x) + 1/2*y(x)^2 = constant + x^2

 

IN:  solve(last, y(x))

OUT: y(x) = [-2 + sqrt(4 - 2*(-constant - x^2)),

                 -2 - sqrt(4 - 2*(-constant - x^2))]

 

            Example:

            Solve differential equations by dsolve().

 

IN:  dsolve(y'(x) = x*exp(y(x)), y(x), x)

OUT: -e^(-y(x)) = constant + x^2

 

IN:  dsolve(y'(x) = y(x)^2+5*y(x)+6, y(x), x)

OUT: ln((4 + 2 y(x))/(6 + 2 y(x))) = constant + x

 

IN:  dsolve(y'(x) = y(x)/x, y(x), x)

OUT: y(x) = constant x sign(x)

 

IN:  dsolve(y'(x) = x + y(x), y(x), x)

OUT: y(x) = -1 - x + constant*e^x

 

 

9.  Sums, Products, and Series

 

            You can compute partial, finite or infinite sums and products. Sums and products can be differentiated and integrated. You construct functions like Taylor polynomials or finite Fourier series. The procedure is the same for sums as products so all examples will be restricted to sums.  The general formats for these functions are:

                        sum(y,x)

                        sum(y)

                        sum(expr, x , xmin , xmax)

                        sum(expr, x , xmin , xmax , dx)

 

                        prod(expr, x , xmin , xmax)

                        prod(expr, x , xmin , xmax , dx)

            The expression expr is evaluated at xmin, xmin+dx, ...  up to the last entry in the series not greater than xmax, and the resulting values are added or multiplied.  The part "step dx" is optional and defaults to 1.  The values of xmin, xmax and dx can be any real number.

            Here are some examples:

             sum(j, j , 1 , 10,1)  

for 1 + 2 + .. + 10.

            sum(3^j, j , 0 , 10 , 2) 

for 1 + 3^2 + ... + 3^10.

            Here are some sample Taylor polynomials:

            sum(x^j/j!, j , 0 , n) 

for exp(x).

            sum((-1)^j*x^(2*j+1)/(2*j+1)!, j , 0 , n)

for sin(x) of degree 2*n+2.

            Remember, the 3 keywords (from, to and step) can be replaced by the comma ,.

 

 

9.1.  Partial Sum

 

            The function

                        sum(f(x),x, a,b)

finds the partial sum (symbolic sum).

 

            Example:

Find the sum of 1^2 + 2^2 ... + n^2.      

 

IN:  sum(x^2, x, 0,n)

OUT: 1/6 *n*(1 + n) *(1 + 2* n)

 

 

9.2.  Indefinite Sum

 

            The function

                        sum(f(x), x) 

finds the indefinite sum, i.e. inverse of the difference F(x+1)-F(x).

 

            Example:

IN:  sum(x)

OUT:  x^2/2-x/2

 

This is different from the partial sum(x,x,0,n).

9.3.  Series

 

            The external functions

                        series(f(x), x)

                        series(f(x), x, order)

to find the Taylor series at x=0. The argument (order) is optional and defaults to 5.

           

            Example:

            Find the power series expansion for cos(x) at x=0.

 

IN:  series(cos(x), x)

OUT: 1 - 1/2 x^2 + 1/24 x^4

 

            The series expansion of f(x) is useful for numeric calculation of f(x). If you can provide derivative of any function of f(x) and f(0), even though f(x) is unknown, you may be able to calculate the function value at any x, by series expansion. Accuracy of calculation depends on the order of series expansion. Higher order, more accuracy, but longer calculation time.

           

            Example:

            calculate f(1), knowing f’=-sin(x) and f(0)=1, where f(x) is unknown.

 

IN:  f'(x_) := -sin(x)

IN:  f(0) := 1

IN:  f(x_) := eval(series(f(x), x))            #  must eval()

OUT: f(x_) := 1 - 1/2 x^2 + 1/24 x^4

 

IN:  f(1)

OUT: 13/24

 

 

9.4.  Polynomials

 

            Polynomials are automatically sorted in order from low to high.

            You can pick up one of coefficient of x in polynomials by

                        coef(poly, x^n)

            e.g.

IN:  coef(x^2+5*x+6, x)

OUT: 5

 

            Note that you cannot pick up the coefficient of x^0 by coef(y,x^0).

            You can pick up one of coefficient of x in polynomials with order < 5 by

                        coef(poly, x,n)

 

            e.g.

IN:  coef(x^2+5*x+6, x,0)

OUT: 6

 

            You can pick up all of coefficients of x in polynomials with order < 5 by

                        coefall(poly, x)

 

            e.g.

IN:  coefall(x^2+5*x+6, x)

OUT: [6, 5, 1]                    # 6 + 5*x + x^2

 

IN:  coefall(a*x^2+b*x+c, x)

OUT: [c, b, a]                    # symbolic values of coefficients

 

            You can pick up the highest order of x in polynomials with order < 5 by

                        order(poly, x)

 

            e.g.

IN:  order(x^2+5*x+6, x)

OUT: 2

 

            You can factor polynomials in order < 5 with respect to x by

                        factor(poly, x)

 

            e.g.

IN:  factor(x^2+5*x+6, x)

OUT: (2 + x) (3 + x)

 

10. Lists and Arrays, Vectors and Matrices

 

            You can construct lists and arrays of arbitrary length, and the entries in the lists and arrays can be of any type of value whatsoever: constants, expressions with undefined variables, or equations.

            A vector or matrix can be represented by a list or array. In a matrix, the number of elements in each row should be the same, e.g. [[a11, a12], [a21, a22]].

 

 

10.1.    Lists

10.1.1.  Entering Lists

 

            You can define a list by putting its elements between two square brackets. e.g. [1,2,3]

            You can define lists another way, with the command:

                        [ list(f(x), x from xmin to xmax step dx) ]

            This is similar to the sum command,  but the result is a list:

                        [f(xmin), f(xmin+dx), ..., f(xmin+x*dx), ...]

which continues until the last value of xmin + x*dx  <= xmax. 

            You also can assign the list to a variable, which variable name become the list name:

 

                        a := [1,2,3]                 # define the list of a

                        b := [f(2), g(1), h(1)]      # assumes f,g,h defined

                        c := [[1,2],3,[4,5]]         # define the list of c

 

            Lists are another kind of value in SymbMath, and they can be assigned to variables just like simple values. (Since variables in SymbMath language are untyped, you can assign any value to any variable.).

            A function can have a list for its value:

                        f(x_) := [sqrt(x), -sqrt(x)]

 

            e.g.

IN:  squreroot(x_) := [sqrt(x), -sqrt(x)]

IN:  squreroot(4)

OUT: [2, -2]

 

            A function can have a list for its argument:

                        abs([-1,2])

            Try

                        a := [ list(j^2, j from 0 to 10 step 1) ]

                        f(x_) := [ list(x^j, j from 0 to 6 step 1) ]

                        b := f(-2)

 

 

10.1.2.     Accessing Lists

 

            You can find the value of the j-th member in a list by

                        member([a,b], j)

The first member of a list is always member(x, 1).

           If you have assigned a list to a variable x, you can access the j-th element by the list index x[j]. The first element of x is always  x[1].  If the x[j] itself is a list, then its j-th element is accessed by repeating the similar step.But you can not use the list index unless the list is already assigned to x.

 

            e.g.

IN:  x := [[1,2],3,[4,5]]    # define the x list

IN:  x[1], x[2]                            # take its first and 2nd element

OUT: [1, 2], 3

 

IN:  x                                        # access the entire list of x

OUT: [[1, 2], 3, [4,5]]

 

IN:  member(x, 2)                     # same as x[2]

OUT: 3

 

            An entire sub-list of a list x  can be accessed with the command x[j], which is the list:

                          [x[j], x[j+1], ... ]

 

 

10.1.3.     Modifying Lists

 

            The subs() replaces the value of the element in the list, as in the variables. e.g.

 

IN:  subs([a,b,c], a = a0)

OUT: [a0, b, c]

 

            Note that you cannot modify lists by assignment.

 

 

10.1.4.     Operating Lists

 

            Lists can be added, subtracted, multiplied, and divided by other lists or by constants.  When two lists are combined, they are combined term-by-term, and the combination stops when the shortest list is exhausted.  When a scalar is combined with a list, it is combined with each element of the list.  Try:

 

            a := [1,2,3]

            b := [4,5,6]

            a + b

            a / b

            3 * a

            b - 4

 

            Example 4.9.2.4.1.

            Two lists are added.

 

IN:  [a1,a2,a3] + [b1,b2,b3]

OUT: [a1 + b1, a2 + b2, a3 + b3]

 

IN:  last[1]

OUT: a1 + b1

 

            If L is a list, then  f(L) results in a list of the values, even though f() is the differentiation or integration function (d() or integrate()).

 

IN:  sqrt([a, b, c])

OUT: [sqrt(a), sqrt(b), sqrt(c)]

 

IN:  d([x, x^2, x^3], x)

OUT: [1, 2*x, 3*x^2]

 

            If you use a list as the value of a variable in a function, SymbMath will try to use the list in the calculation.

            You can sum all the elements in a list x by

                        listsum(x)

            Example:

 

IN:  listsum([a,b,c]^2)

OUT: a^2 + b^2 + c^2

 

            This function takes the sum of the squares of all the elements in the list x.

            You can do other statistical operations (see Section 4.10. Statistics) on the list, or plot the list of numeric data (see Section 5. Plot).

            You can find the length of a list (the number of elements in a list) with:

                        length(a)


10.2.    Arrays

10.2.1.  Entering Arrays

 

            You can define an array of a by assigning its element value into its index:

            a[1]:=1

            a[2]:=4

or you can define arrays another way, with the command:

                        do(a[x]:=f(x), x from xmin to xmax step dx)

 

            e.g.

            do(a[j] := 2*j, j from 1 to 2)

            You can define 2-dimentional array by

                        a[1,1]:=11

                        a[1,2]:=12

                        a[2,1]:=21

                        a[2,2]:=22

or

            do(do(a[j,k]:=j+k, j,jmin,jmax,dj), k,kmin,kmax,dk)

 

 

10.2.2.  Accessing Arrays

 

            After defining an array of a, you can access one of its element by its index

 

IN:  a[1]

OUT: 1

 

            You also can list out all of its elements by

                        list(a[j], j,1,2,1)

 

            e.g.

IN:  do(a[j]:=2*j, j,1,2,1)

IN:  list(a[j], j,1,2)

OUT: 1, 4

 

 

10.2.3.  Modifying Arrays

 

            You can modify an array by assigning new value into its index

 

IN:  a[1]:=2

 

 

10.2.4.  Operating Arrays

 

            e.g.

            after defining 2 arrays a and b, find their dot time, a .* b.

IN:  a[1]:=1, a[2]:=2                 # define array a

IN:  b[1]:=11, b[2]:=12               # define array b

IN:  p:=0

IN:  do(p:=p + a[j]*b[j], j,1,2,1)    # a .* b

 

 

10.3.     Vectors and Matrices

 

            You can uses arrays or lists to represent vectors, and lists of lists to represent matrices.

            Vectors and matrices can be operated by "+" and "-" with vectors and matrixes, by "*" and "/" with a scalar, and by d() and integrate(). These operations are on each element, as in lists.

            You can use lists as vectors, adding them and multiplying them by scalars. For example, the dot product of two vectors of a and b is:

                        sum(a[j]*b[j], j from 1 to jmax)

            You can even make this into a function:

                        dottime(x_, y_) := listsum(x*y)

 

            e.g.

            represent the dot product of two vectors by arrays

IN:  a[1]:=1, a[2]:=2                   # define array a

IN:  b[1]:=11, b[2]:=12               # define array b

IN:  p:=0

IN:  do(p:=p + a[j]*b[j], j,1,2,1)    # a .* b

 

            represent the dot product of two vectors by lists

IN:  dottime([1,2], [11,12])          # by lists in function dottime()

 

            How about the cross product:

cross(a,b) = [a[2]*b[3]-b[2]*a[3],a[3]*b[1]-b[3]*a[1],a[1]*b[2]-b[1]*a[2]]

 

 

11.    Statistics

 

            Some statistical functions are:

                        average(x), max(x), min(x), listsum(x), length(x)

 

            A list of numbers can be calculation on statistics.

           

            Example:

IN:  p := [1, 2, 3]

IN:  average(p), max(p), min(p), length(p)

OUT: 2, 3, 1, 3

 

            Not only a list of number but also a list of symbolic data can be operated by some statistic functions to show how to do the statistic operation.

 

IN:  p := [a, b, c]

IN:  average(p)

OUT: 1/3*(a + b + c)

 

IN:  listsum(p)

OUT: a + b + c

 

IN:  length(p)

OUT: 3

 

 

12.     Tables of Function Values

 

            If you want to look at a table of values for a formula, you can use the table command:

                        table(f(x), x)

                        table(f(x), x from xmin to xmax)

                        table(f(x), x from xmin to xmax step dx)

            It causes a table of values for f(x) to be displayed with x=xmin, xmin+dx, ..., xmax.  If xmin, xmax, and step omit, then xmin=-5, xmax=5, and dx=1 for default. You can specify a function to be in table(),

 

            Example:

Make a table of x^2.

 

IN:  table(x^2, x)

OUT:

-5,        25

-4,        16

-3,        9

-2,        4

:           :

:           :

 

            Its output can be written into a disk file for interfacing with other software (e.g. the numeric computation software).

 

 

13.   Conversion

 

            Different types of data may be converted each other.

 

 

13.1.  Converting to Numbers

 

            The complex number is converted to the real number by

                        re(z), im(z), abs(z), arg(z), sign(z)

            The real number is converted to the integer number by

                        trunc(x)

                        round(x)

            The real number is converted to the rational number by

                        ratio(x)

            The rational number is converted to the real number by

                        num(x)

                        numeric:=on

            The rational number is converted to the integer number by

                        nume(x)

                        deno(x)    

            The string is converted to the real number if possible, by

                        number("123")

 

 

13.2.  Converting to Lists

 

            You can convert sum to a list of terms by

                        term(a+b)

 

IN:  term(a+b)

OUT: [a, b]

 

            You can convert product to a list of multipliers by

                        mult(a*b)

 

IN:  mult(a*b)

OUT: [a, b]

 

            You can convert an array x to a list by

                        [ list(x[j], j,1,jmax,1) ]

 

 

13.3.  Converting to Strings

 

            You can convert numbers to strings by

                        string(123)

 

IN:  string(123)

OUT: "123"

 

 

13.4.  Converting to Table

 

            A list of real numbers can be converted to a table by

                        table()

           

            Example:

 

IN:  x := [5,4,3,2,1]

IN:  table(x[j], j from 1 to 4 step 1)

OUT:

1,      5

2,      4

3,      3

4,      2

 

 

14.    Getting Parts of Expression

14.1.  Getting Type of Data

 

            You can get type of data by

                        type(x)

 

IN:  type(2)

OUT: "integer"

 

 

14.2.  Getting Operators

 

            You also can get operators by

                        type(x)

 

IN:  type(a>b)

OUT: ">"

 

IN:  type(sin(x))

OUT: "sin()"

 

 

14.3.  Getting Operands

 

            The functions

                        left(x=a), left(a > b)

                        right(x=a), right(a > b)

pick up the left- and right- side of the equation and inequality.

 

IN:  left(a>b), right(a>b)

OUT: a, b

 

            You can get the j-th term of sum by

                        member(term(a+b), j)

 

IN:  member(term(a+b), 1)

OUT: a

 

            You can get the arguments of a function by

                        argue(f(x))

 

IN:  argue(sin(x))

OUT: x

 

 

14.4.  Getting Coefficients

 

            A coefficient of x^n in an expression can be picked up by

                        coef(p, x^n)

 

            e.g.

IN:  coef(a + b*x + c*x^2 + d*x^3, x)

OUT: b

 

            You can get a coefficient of x^n (where 0<= n < 4) in polynomials ordered up to 4 by

                        coef(poly, x,n)

(see Chapter Polynomials for detail).

 

                       

15.    Database

 

            After you create a database file as a library (external function), you can search your data by finding its function value.

 

 

15.1.  Phone Number

 

            If you have created the database file "phoneNo" as follow:

 

-------------------------------------

phoneno("huang") := "6974643"

phoneno("john")  := "12345"

--------------------------------------

 

            You can find out phone No. of someone from the phone No. database file "phoneNo" by the external function

                        phoneno("name")

 

            Example:

            find out phone No. of huang.

IN:  phoneno("huang")

OUT: 6974643

 

 

15.2.  Atomic Weight

 

            You can search atomic weight of chemical element from the database file "atom_wei".

            e.g.

            What is atomic weight of chemical element H ?

IN:  atom_wei(H)

OUT: 1

 

 

15.3.  Chemical Reaction

 

            You can predict products for chemical reactions from the database file "react".

 

            Example 4.14.2. 

            What are the products when HCl + NaOH react ?

IN:  react(HCl+NaOH)

OUT: H2O + NaCl

 

 

16.  Learning from User

 

            One of the most important feature of SymbMath is its ability to deduce and expand its knowledge. If you provide it with the necessary facts, SymbMath can solve many problems which were unable to be solved before. The followings are several ways in which SymbMath is able to learn from your input.

 

 

16.1.  Learning Integrals from a Derivative

 

            Finding derivatives is much easier than finding integrals. Therefore, you can find the integrals of a function from the derivative of that function.

            If you provide the derivative of a known or unknown function, SymbMath can deduce the indefinite and definite integrals of that function. If the function is not a simple function, you only need to provide the derivative of its simple function. For example, you want to evaluate the integral of f(a*x+b), you only need to provide f’.

 

            If you know a derivative of an function f(x) (where f(x) is a known or unknown function), SymbMath can learn the integrals of that function from its derivative.

 

            Example:

            check SymbMath whether or not it had already known integral of f(x)

IN:  integrate(f(x), x)

OUT: integrate(f(x), x)

 

IN:  integrate(f(x), x, 1, 2)

OUT: integrate(f(x), x, 1, 2)

 

            As the output displayed only what was typed in the input without any computed results, imply that SymbMath has no knowledge of the indefinite and definite integrals of the functions in question. Now you teach SymbMath the derivative of f(x) on the first line, and then run the program again.

 

IN:  f'(x_) := exp(x)/x

IN:  integrate(f(x), x)

OUT: x*f(x) - e^x

 

IN:  integrate(f(x), x, 1, 2)

OUT: e - f(1) + 2*f(2) - e^2

 

            As demonstrated, you only supplied the derivative of the function, and in exchange SymbMath logically deduced its integral.

            Another example is

 

IN:  f'(x_) := 1/sqrt(1-x^2)

IN:  integrate(f(x), x)

OUT: sqrt(1 - x^2) + x*f(x)

 

IN:  integrate(k*f(a*x+b), x)

OUT: k*(sqrt(1 - (b + a*x)^2) + (b + a*x)*f(b + a*x))/a

 

IN:  integrate(x*f(a*x^2+b), x)

OUT: sqrt(1-(a*x^2 + b)^2) + (a*x^2 + b)*f(a*x^2 + b)

 

            The derivative of the function that you supplied can be another derivative or integral.

 

            Example:

 

IN:  f'(x_) := eval(integrate(cos(x),x))

OUT: f'(x_) := sin(x)

 

IN:  integrate(f(x), x)

OUT: -sin(x)

 

IN:  integrate(f(a*x + b), x)

OUT: -sin(b + a*x)/a

 

IN:  integrate(x*f(x), x)

OUT: -cos(x) - x*sin(x)

 

IN:  integrate(x^1.5*f(x), x)

OUT: 1.5*integrate(sqrt(x)*sin(x), x) - x^1.5*sin(x)

 

IN:  integrate(x^2*f(x), x)

OUT: -2*x*cos(x) + 2*sin(x) - x^2*sin(x)

 

IN:  integrate(x*f(x^2), x)

OUT: -sin(x^2)

 

IN:  integrate(x^3*f(x^2), x)

OUT: -0.5*cos(x^2) - 0.5*x^2*sin(x^2)

 

IN:  integrate(f(x)/(x^1.5), x)

OUT: -2/sqrt(x)*f(x) + 2*integrate(sin(x)/sqrt(x), x)

 

IN:  integrate(f(x)/(x^2), x)

OUT: -f(x)/x + si(x)

 

 

16.2.  Learning Complicated Integrals from a Simple Integral

 

            You supply a simple indefinite integral, and in return, SymbMath will perform the related complicated integrals.

 

            Example:

            Check whether SymbMath has already known the following integrals or not.

 

IN:  integrate(f(x), x)

OUT: integrate(f(x), x)

 

IN:  integrate((2*f(x)+x), x)

OUT: integrate((2*f(x)+x), x)

 

IN:  integrate(integrate(f(x)+y), x), y)

OUT: integrate(integrate(f(x)+y), x), y)

 

            Supply, like in the previous examples, the information: integral of f(x) is f(x) - x; then ask the indefinite integral of 2*f(x)+x, and a double indefinite integral of 2*f(x) + x, and a double indefinite integral of respect to both x and y. Change the first line, and then run the program again.

 

IN:  integrate(f(x_), x_) := f(x) - x

IN:  integrate(2*f(x)+x, x)

OUT: 2*f(x) - 2*x + 1/2*x^2

 

IN:  integrate(integrate(f(x)+y, x), y)

OUT: f(x)*y - x*y + x*y^2

 

            You can also ask SymbMath to perform the following integrals:

integrate(integrate(f(x)+y^2, x), y),

integrate(integrate(f(x)*y, x), y),

integrate(x*f(x), x),

triple integral of f(x)-y+z, or others.

 

 

16.3.  Learning Definite Integral from Indefinite Integral

 

            You continue to ask indefinite integral.

 

IN:  integrate(integrate(f(x)+y, x from 0 to 1), y from 0 to 2)

OUT: 2 f(1)

 

 

16.4. Learning Complicated Derivatives from Simple Derivative

 

            SymbMath can learn complicated derivatives from a simple derivative, even though the function to be differentiated is an unknown function, instead of standard function.

 

            Example :

            Differentiate f(x^2)^6, where f(x) is an unknown function.

 

IN:  d(f(x^2)^6, x)

OUT: 12 x f(x^2)^5 f'(x^2)

 

            Output is only the part derivative. f'(x^2) in the output suggest that you should teach SymbMath f'(x_). e.g. the derivative of f(x) is another unknown function df(x), i.e. f'(x_) = df(x), assign f'(x_) with df(x) and run it again.

 

IN:  f'(x_) := df(x)

IN:  d(f(x^2)^6, x)

OUT: 12 x f(x^2)^5 df(x^2)

 

            This time you get the complete derivative.

 

           

16.5.  Learning Integration from Algebra

 

            If you show SymbMath algebra, SymbMath can learn integrals from that algebra.

 

            Example :

            Input f(x)^2=1/2-1/2*cos(2*x), then ask for the integral of f(x)^2.

 

IN:  f(x)^2 := 1/2-1/2*cos(2*x)

IN:  integrate(f(x)^2, x)

OUT: 1/2 x - 1/4 sin(2 x)

 

            SymbMath is very flexible. It learned to solve these problems, even though the types of problems are different, e.g. learning integrals from derivatives or algebra.

 

 

16.6.  Learning Complicated Algebra from Simple Algebra

 

            SymbMath has the ability to learn complicated algebra from simple algebra.

 

            Example:

            Transform sin(x)/cos(x) into tan(x) in an expression.

 

IN:  sin(x)/cos(x) := tan(x)

IN:  x+sin(x)/cos(x)+a

OUT: a + x + tan(x)

 

 

16.7.  Learning vs. Programming

 

            The difference between learning and programming is as follows: the learning process of SymbMath is very similar to the way human beings learn, and that is accomplished by knowing certain rule that can be applied to several problems. Programming is different in the way that the programmer have to accomplish many tasks before he can begin to solve a problem. First, the programmer defines many subroutines for the individual integrands (e.g. f(x), f(x)+y^2, 2*f(x)+x, x*f(x), etc.), and for individual integrals (e.g. the indefinite integral, definite integral, the indefinite double integrals, indefinite triple integrals, definite double integrals, definite triple integrals, etc.), second, write many lines of program for the individual subroutines, (i.e. to tell the computer how to calculate these integrals), third, load these subroutines, finally, call these subroutines. That is precisely what SymbMath do not ask you to do.

            In one word, programming means that programmers must provide step-by-step procedures telling the computer how to solve each problems. By contrast, learning means that you need only supply the necessary facts (usually one f’ and/or one integral of f(x)), SymbMath will determine how to go about solutions of many problems.

            If the learning is saved as a library, then you do not need to teach SymbMath again when you run SymbMath next time.

 

 


PART 2    Programmer's Guide

 

17.  Programming in SymbMath

 

            SymbMath is an interpreter, and runs a SymbMath program in the Input window, which is written by any editor in the text (ASCII) file format.

            SymbMath language is a procedure language, which is executed from top to bottom in a program, like BASIC, FORTRAN, or PACSAL. It also is an expression-oriented language and functional language.

            The SymbMath program consists of a number of statements. The most useful statement contains expressions, the expression includes data, and the most important data is functions.

            The structure of SymbMath language is:

                        data -> expression -> statement -> program

            Note that upper and lower case letters are different in SymbMath language, (e.g. abc is different from ABC) until the switch lowercase := on.

            In the following examples, a line of "IN: " means input, which you type in the Input window, then leave the Input window by <Esc>, finally run the program by the command "Run"; while a line of "OUT:" means output. You will see both input and output are displayed on two lines with beginning of "IN: " and "OUT: " in the Output window. You should not type the word "IN: ". Some outputs may be omit on the examples.

# is a comment statement.

            You can split a line of command into multi-lines of command by the comma ,. The comma without any blank space must be the last character in the line.

 

 

17.1.  Data Types

 

            The data types in SymbMath language is the numbers, constants, variables, functions, equations, arrays, array index, lists, list index, and strings. All data can be operated. It is not necessary to declare data to be which type, as SymbMath can recognise it.

 

 

17.1.1.  Numbers

 

            The types of numbers are integer, rational, real (floating-point), and complex numbers in the range from -infinity to infinity.

            In fact, the range of the input real numbers is

-inf, -(10^300)^(10^300) to -10^(-300), 0, 10^(-300) to (10^300)^(10^300), inf.

            The range of the output real numbers is the same as input when the switch numeric := off, but when the switch numeric := on, it is

            -inf, -1.E300 to -1.E-300, 0, 1.E-300 to 1.E300, inf.

            It means that the number larger than 1.e300 is converted automatically to inf, the absolute values of the number less than 1.e-300 is converted to 0, and the number less than -1e300 is converted to -inf.

 

 

            For examples:

-------------------------------------------

Numbers          Type

 

23                    integer

2/3                   rational

0.23                  real

2.3E2               real

2+3*i                complex

2.3+i                 complex

---------------------------------------------

 

            That "a" and "b" are the same means a-b = 0, while that they are different means a-b <> 0.

            For the real numbers, the upper and lower case letters E and e in exponent are the same, e.g. 1e2 is the same as 1E2.

 

 

17.1.2.  Constants

 

            The constants are the unchangeable values. There are some built-in constants. The name of these built-in constants should be avoided in the user-defined constants.

 

------------------------------------------------------------------

Built-in Constants                     Meanings

 

pi:=3.1415926536                      the circular constant.

e:=2.7182818285                      the base of the natural logarithms.

i:=sqrt(-1)                                 the imaginary sign of complex numbers.

inf                                            infinity.

-inf                                           negative infinity.

c_inf                                         complex infinity, both real and imaginary parts

                                                of complex numbers are infinity. e.g. inf+inf*i.

constant                                   the integral constant.

discont                                     discontinuity, e.g. 1/0. (You can evaluate the one-sided value                                         by x=x0+zero or x0-zero if the value of expression is discont).

x0-zero                                     to evaluate left-sided value when x approach x0

                                                from negative (-inf) direction, as zero -> 0.

x0+zero                                    to evaluate right-sided value when x approach x0

                                                from positive (+inf) direction, as zero -> 0.

undefined                                  the undefined value, e.g. indeterminate forms:

                                                0/0, inf/inf, 0*inf, 0^0, etc.

--------------------------------------------------------------------

 

            Zero is the positive-directed 0, as the built-in constant. f(x0+zero) is the right-hand sided function value when x approaches to x0 from the positive direction, i.e. x = x0+. f(x0-zero) is the left-sided function value when x approaches to x0 from the negative direction, i.e. x = x0-. e.g. f(1+zero) is the right-hand sided function value when x approaches to 1 from the positive (+infinity) direction, i.e. x = 1+, f(1-zero) is the left-hand sided function value when x approaches to 1 from the negative (-infinity) direction, i.e. x = 1-; exp(1/(0+zero)) gives inf, exp(1/(0-zero)) gives 0.

            The inf, discont and undefined can be computed as if numbers.

 

            Example:

IN:  inf+2, discont+2, undefined+2

OUT: inf, discont, undefined

 

            Notice that the discont and undefined constants are different. If the value of an expression at x=x0 is discont, the expression only has the one-sided value at x=x0 and this one-sided value is evaluated by x=x0+zero or x=x0-zero. If the value of an expression at x=x0 is undefined, the expression may be evaluated by the function lim().

 

            Example: evaluate exp(1/x) and sin(x)/x at x=0.

 

IN:  f(x_) := exp(1/x)

OUT: f(x_) := exp(1/x)

 

IN:  f(0)

OUT: discont           # f(0) is discontinuity, only has one sided value

 

IN:  f(0+zero)          # right-sided value

OUT: inf

 

IN:  f(0-zero)          # left-sided value

OUT: 0

 

IN:  subs(sin(x)/x, x = 0)

OUT: undefined

 

IN:  lim(sin(x)/x, x = 0)              # it is evaluated by lim()

OUT: 1

 

 

17.1.3.  Variables

 

            The sequence of characters is used as the name of variables. Variable names can be up to 128 characters long. They must begin with a letter and use only letters and digits.  SymbMath knows upper and lower case distinctions in variable names, so AB, ab, Ab and aB are the different variables. They are case sensitive until the switch lowercase is set to on (i.e. lowercase := on).

            Variables can be used to store the results of calculations. Once a variable is defined, it can be used in another formula. Having defined X as above, you could define Y := ASIN(X). You can also redefine a variable by storing a new value in it.  If you do this, you will lose the original value entirely.

            Assign a result to a variable, just put

            <var-name> :=  expression

            e.g.               x := 2 + 3      # assign value to x

            Variables can be used like constants in expressions.

            For example:

                               a := 2 + 3

                               b := a*4

            If an undefined variable is used in an expression, then the expression returns a symbolic result (which may be stored in another variable).  Pick an undefined variable name, say x, and enter:

 

                        y := 3 + x          # formula results since x undefined

                        x := 4               # Now x is defined

                        y                      # y returns 7, but its value is still the formula 3 + x

                        x := 7               # revalue x

                        y                      # new value for y

 

            Note that in symbolic computation, the variable has not only a numeric value but also a symbolic value.

            Symbolic values for variables are useful mostly for viewing the definitions of functions and symbolic differentiation and integration.

            Watch out for infinite recursion here.  Defining

                        x := x+3

when x has no initial value, it will not cause an immediate problem, but any future reference to x  will result in an infinite recursion !

            A value can be assigned to the variable, by one of three methods:

            (1) the assignment :=,

            (2) the user-defined function f(),

            (3) subs(y, x = x0).

 

e.g.

y:=x^2

x:=2                             # assignment

y

f(2)                               # if f(x) has been defined, e.g. f(x_):=x^2.

subs(x^2, x = 2)                        # evaluate x^2 when x = 2.

 

            The variable named last is the built-in as the variable last is always automatically assigned the value of the last output result.

            The usual used independent variable is x.

            By default, |x| < inf and all variables are complex, except that variables in inequalities are real, as usual only real numbers can be compared. e.g. x is complex in sin(x), but y is real in y > 1.

            You can restrict the domain of a variable by assuming the variable is even, odd, integer, real number, positive or negative (see Chapter Simplification and Assumption).

 

 

17.1.4.  Patterns

 

            Patterns stand for classes of expressions.

 

_          any expression.

x_        any expression, given the name x.

 

            Patterns should appear on the left-hand side of the assignment only, not on the right-hand side of the assignment. Patterns are only used in definition of functions, procedures and rules.

            Patterns are used to define functions and rules for pattern match.

 

 

17.1.5.  Functions, Procedures and Rules

 

            These are two types of functions: internal and external. The internal function is compiled into the SymbMath system. The external function is the library written in SymbMath language, which is automatically loaded when it is needed. (See Chapter Library and Package). The usage of both types are the same. You can change the property or name of the external function by modifying its library file, or you add a new external function by creating its library file, but you cannot change the internal function.

 

 

17.1.5.1.  Standard Mathematical Functions

 

            Different versions of SymbMath have different number of standard mathematical functions. The Advanced Version C has all of them. See the following table in detail for other versions. All below standard functions, (except for random(x), n!, fac(n) and atan2(x,y)), can be differentiated and integrated symbolically.

 


             Table 17.1.5.1  Standard Mathematical Functions

-----------------------------------------------------------------------

Functions                     Meanings

 

random(x)                     generate a random number.

n!                                 factorial of n.

fac(n)                           the same as n!.

sqrt(x)                          square root, the same as x^0.5.

root(x,n)                       all n'th root of x.

exp(x)                          the same as e^x.

sign(x)                         1 when re(x) > 0, or both re(x) = 0 and im(x) > 0; 0 whenx=0;

                                    -1 otherwise.

abs(x)                          absolute value of x.

ln(x)                             natural logarithmic function of x, based on e.

log10(x)

sin(x)                           sine function of x.

cos(x)

 

...............................   above functions in Shareware Version A ...............

 

tan(x)

csc(x)

sec(x)

cot(x)

asin(x)              arc sine function of x, the inverse of sin(x).

acos(x)

atan(x)

acot(x)

asec(x)

acsc(x)

atan2(x,y)

 

............................. above functions in Student Version B .................

 

sinh(x)              hyperbolic sine function of x.

cosh(x)

tanh(x)

csch(x)

sech(x)

coth(x)

asinh(x)                        arc hyperbolic sine function of x, the inverse of sinh(x).

acosh(x)

atanh(x)

acoth(x)

asech(x)

acsch(x)

--------------------------------------------------------------------------

 

 

 

17.1.5.2.  Calculus Functions

 

            Calculus functions are for calculus calculation. The first argument of the function is for evaluation, and the second argument is a variable that is with respect to.

 

 

 

 

 

 

                        Table 17.1.5.2       Calculus Functions

--------------------------------------------------------------------------------------------------------------

Functions         Meanings

 

replace(y, x , x0)          evaluates y when x = x0.

lim(y, x = x0)    gives the limit of y when x approaches x0. Note that the correct answers                                   usually for the indeterminate forms: 0/0, inf/inf, 0*inf, 0^0, inf^0.

 

d(y, x)              differentiate y with respect to x.

d(y, x, order)    gives the n-th order derivative of y with respect to an undefined variable x.

d(y)                  implicit differentiation,  the default variable is x .

 

integrate(y, x)   find the indefinite integral of y with respect to an undefined variable x.

integrate(y,x,a,b)          find the definite integral of y with respect to an undefined variable x taken             from x=a to x=b.

integrate(y,x,a,b,c)       find the definite integral of y with respect to an undefined variable x taken             from x=a to x=b, then to x=c, where b is singularity.

integrate(y, x , a , b)     the same as integrate(y,x,a,b).

integrate(y)                   implicit integration,  the default variable is x.

 

dsolve(y'=f(x,y), y, x)    solve a differential equation.

 

sum(y,x)           indefinite sum with a variable x.

sum(y)             indefinite sum y,  the default variable is x.

sum(y, x , xmin , xmax)                        partial   sum of y from xmin to xmax .

sum(y,x,0, inf)              infinite sum.

sum(y, x , xmin , xmax , dx)                  sum of y, by step dx.

 

prod(y, x , xmin , xmax)                                    product of y step=1.

prod(y, x , xmin , xmax , dx)                 product of y.

----------------------------------------------------------------------------------------------------------------

 

            If a second argument x is omitted in the functions d(y) and integrate(y), they are implicit derivatives and integrals. If f(x) is undefined, d(f(x), x) is differentiation of f(x). These are useful in the differential and integral equations. (see later chapters).

 

            For examples:

            integrate(integrate(F,x), y) is double integral of F with respect to both variables x and y.

            d(d(y,x),t) is the mixed derivative of y with respect to x and t.

 

                        Examples:

--------------------------------------------------------------------------------

differentiation                d()                    d(x^2,x)

integration                    integrate()        integrate(x^2,x)

limit                              lim()                 lim(sin(x)/x, x = 0)

---------------------------------------------------------------------------------

 

 

17.1.5.3.  Test Functions

 

                        Table 17.1.5.3.1  The is*(x) Functions

---------------------------------------------------------------------

Function                       Meaning

 

isodd(x)                                    test if x is an odd number.

iseven(x)                      test if x is an even number.

isinteger(x)                   test if x is an integer number.

isratio(x)                       test if x is a rational number.

isreal(x)                                    test if x is a real number.

iscomplex(x)                 test if x is a complex number.

isnumber(x)                  test if x is a number.

islist(x)                         test if x is a list.

isfree(y,x)                     test if y is free of x.

issame(a,b)                  test if a is the same as b.

islarger(a,b)                  test if a is larger than b.

isless(a,b)                    test if a is less than b.

----------------------------------------------------------------------

 

            All of the is* functions give either 1 if it is true or 0 otherwise.

            The type(x) gives the type of x. Its value is a string.

 


            Table 17.1.5.3.2  The type(x) functions

--------------------------------------------------

x                      type(x)

 

1                      integer

1.1                   real

2/3                   ratio

1+i                   complex

sin(x)               sin()

[1,2]                 []

a                      symbol

"a"                    string

a+b                  +

a*b                   *

a^b                   ^

a=b                  =

a==b                ==

a>b                  >

a>=b                >=

a<b                  <

a<=b                <=

a<>b                <>

a,b                   ,

---------------------------------

 

            You also can test x, e.g. if x is type of real number, by

                        type(x)=="real"

 

 

17.1.5.4.  Miscellaneous Functions

 

                        Table 17.1.5.4.1      Algebra Functions

---------------------------------------------------------------------------------------------------

expand(F)                     expand (a+b)^2 to a^2 + 2*a*b + b^2.

factor(F)                       factorise a^2 + 2*a*b + b^2 to (a+b)^2.

solve(f(x)=0, x)             solve polynomial and systems of linear equations

---------------------------------------------------------------------------------------------------

Note: the Shareware Version has not solve().

 

            For example:

-----------------------------------------------------------------------

solving             solve()              solve(x^2+1 = 0, x)

expanding         expand()           expand((a+b)^2)        

factoring           factor()             factor(a*c+b*c)        

----------------------------------------------------------------------

 

            Conversion functions convert a type of data to another type of data.

 

                        Table 17.1.5.4.2   Conversion Functions

---------------------------------------------------------------------

listsum([a,b])                convert list to sum.

coef(expr, x^2)             gives the coefficient of x^2 in expr.

left(x^2=b)                    left hand side of an equation.

right(x^2=b)                  right hand side of an equation.

re(x)                             real part of complex numbers.

im(x)                            imaginative part of complex numbers.

num(x)                         convert x to the floating-point number.

ratio(x)                         convert x to the rational number.

round(x)                       convert x to the rounded integer.

trunc(x)                                    convert x to the truncated integer.

----------------------------------------------------------------------

 

                        Table 17.1.5.4.3     The List and Table Functions

-------------------------------------------------------------------------------------------

list(f(x), x from xmin to xmax step dx)   lists of f(x).

table(f(x), x from xmin to xmax step dx) data table of function values.

--------------------------------------------------------------------------------------------

 

            Above functions can be operated and chained, like the standard functions.

 

 

17.1.5.5.     User-defined Functions

 

            You can define the new functions, which include the standard functions, calculus functions, and algebraic operators.

            Define a new function f(x) by 

                        f(x_) := x^2

and then call f(x) as the standard functions. The function name can be any name, except for some keywords. (for the maximum number of arguments, see Chapter  System Limits).

            Clears a variable or function from assignment by

                        clear(x)            # clear x from assignment.

                        clear(f(x))         # clear f(x) from assignment.

                        clear(a>0)         # clear a>0 from assignment.

            Variables can be used in function definitions. It leads to an important difference between functions and variables.  When a variable is defined, all terms of the definition are evaluated.  When a function is defined, its terms are not evaluated; they are evaluated when the function is evaluated. That means that if a component of the function definition is changed, that change will be reflected the next time the function is evaluated.

 

 

17.1.5.6.  Procedures

 

            A procedure is similar to a function, but the right side of assignment in its definition is multi statements grouped by block(). The block(a,b,c) groups a,b,c and only returns the last argument as its value, or returns the second last argument as its value if the last argument is local(). It is used as grouper in definition of a procedure. All variables in block are local.

 

            e.g. f(x_):=block(p:=x^6,p)

            Remember that you can split a line of program into multi-lines program at comma,.

 

 

17.1.5.7.  Rules

 

            A rule is similar to a function. In definition of function, all arguments of function are simple variables, but in definition of rules, the first argument may be a complicated expression.

 

            e.g.

            f(x_,y_) := x^2+y^2                               # defining function

            f(x_,y_) := block(a:=2, a+x^2+y)                        # defining procedure

            log(x_ * y_) := log(x)+ log(y)                 # defining rule

 

 

 

17.1.6.  Equations

 

            An equation is an equality of two sides linked by an equation sign =, e.g. x^2+p = 0, where the symbol = stands for an equation. Note that the symbols "=", "==" and ":=" are different: ":=" is the assignment, "==" is the equal sign, but "=" is the equation sign.

 

            Example:

IN:  2 = 2

OUT: 2 = 2                   # unevaluated

 

IN:  2 == 2

OUT: 1                         # evaluated to 1 (true)

 

            Systems of equations are a list of equations, e.g.

[a1*x+a2*y=a3, b1*x+b2*y=b3].

 

 

17.1.7.  Inequalities

 

            e.g.

                        a < b                less than

                        a <= b              less than or equal to

                        a > b                greater than

                        a >= b              greater than or equal to

                        a == b              equal to

                        a <> b              not equals

 

 

17.1.8.  Vectors or Lists

 

            Lists are similar to lists in such language as PROLOG.

            [a, b, c] is a list.

            [a, b, [c1, c2]] is a list of lists.

            The list index is the index for n-th element in a list. e.g. b[2] indicates the second element in the list b.

            The built-in list index is last[number]. The name of last output list is last, e.g. last[1] is the first element in the last output list.

 

 

17.1.9.  Matrices or Arrays

 

            Arrays are the same as those in such language as PASCAL and FORTRAN. But you can use arrays without declaring arrays, unlike in PASCAL and FORTRAN.

 

            e.g.

a[1]:=1

a[2]:=4

 

            The array index is the index for n-th element in an array. e.g. a[2] indicates the second element in the array a.

 

 

17.1.10.  Strings

 

            A string is a sequence of characters between two quotation marks. e.g. "1234567890". Note that 1234 is number but "1234" is string. The number can be calculated and only has 11 of max digits, while string cannot be calculated and has 64000 of max characters long.

            Note that the output of strings in SymbMath is without two quotation marks. This makes text output to graph and database more readable.

            Strings can be stored in variables, concatenated, broken, lengthen, and converted to numbers if possible.

 

            e.g.

IN:  p := "abc"               # "abc" is stored in variable p

OUT: p := abc

 

IN:  concat("s","t")         # concatenate "s" and "t"

OUT: st

 

IN:  length("abc")          # count length of "abc"

OUT: 3

 

IN:  number("123")        # convert string "123" into number 123

OUT: 123      

 

IN:  type(a), type("a")

OUT: symbol, string

 

 

17.2.   Expressions

 

            The expressions (i.e. expr) are made up of operators and operands. Most operator are binary, that is, they take two operands; the rest are unitary and take only one operand. Binary operators use the usual algebraic form, e.g. a+b.

            There are two kinds of expressions: numeric and Boolean. The numeric expression is combination of data and algebraic operators while the Boolean expression is combination of data and relational operators and logic operators. These two kinds of expressions can be mixed, but the numeric expression has higher priority than Boolean operators. x*(x>0) is different from x*x>0. x*x>0 is the same as (x*x)>0.

            e.g.

a+b+3               numeric expression,

a>0                  Boolean expression

a>0 and b>0     Boolean expression

(x>0)*x             mixed numeric and Boolean expression

 

                       

17.2.1.   Operators

 

            Table 17.2.1       Operators

--------------------------------------------------------------------------------------------------

Operation                     Operators         Examples         Order

 

comma                         ,                       a:=2, b:=3         1

assignment                   :=                     p:=2+3              2

and                               and                   a>2 and a<8     2

or                                 or                     a>2 or b>2        2

equation                       =                      x^2+x+1 = 0     3

equal                            ==                    a==2                3

larger than                    >                      a>2                  3

larger and equal            >=        a>=2                3

less than                      <                      a<2                  3

less and equal              <=                    a<=2                3

unequal                                    <>                    a<>2                3

plus                              +                      a+b                  4

minus                           -                       a-b                   4

mutilation                      *                       a*b                   5

division                         /                       a/b                   5

power                           ^                      a^b                   6

factorial                                    !                       n!                     6

positive                        +                      +a                    7

negative                       -                       -a                     7

function                                    f()                     sin(x)               7

list index                       f[]                     f[1]                   7

parentheses                  ()                      (a+b)*c             7

list                                []                      [a,b]                 7

------------------------------------------------------------------------------------------------

 

            All functions have the same 7th order.

            Operations with higher order precede, otherwise operations with equal precedence are performed from left to right.  These are the usual algebraic conventions.

            a^b^c is the same as (a^b)^c.

            You can get operators by type(x).

 

 

17.2.1.1.  Arithmetic Operators

 

-------------------------------------------------------------------------------------------

plus                              +                      a+b                  4

minus                           -                       a-b                   4

mutilation                      *                       a*b                   5

division                         /                       a/b                   5

power                           ^                      a^b                   6

fractorial                       !                       a!                     6

---------------------------------------------------------------------------------------------

 

 

17.2.1.2.  Relational Operators

 

            Before you can write loops, you must be able to write statements that evaluate to 1 or 0, and before you can do that, you must be able to write useful statements with logical values. In mathematics, these are relational statements.

            SymbMath allows you to compare numbers six ways:

 

                        a < b                less than

                        a <= b              less than or equal to

                        a > b                greater than

                        a >= b              greater than or equal to

                        a == b              equal to

                        a <> b              not equals

 

            SymbMath uses the double equals sign == (like C language) for "is equal to" to distinguish this operator from the equation =.

            The result of a comparison of two real numbers is either 1 or 0. If the comparison is not both real numbers, it left unevaluated.

 

 

17.2.1.3.    Logical Operators

 

            SymbMath uses the logical operators:  AND, and OR.  You can combine comparison operators with them to any level of complexity. In contrast to Pascal, logical operators in SymbMath have a lower order or precedence than the comparisons, so a < b  and  c > d works as expected.  The result of combining logical values with

logical operators is another logical value (1 or 0).  Bit operations on integers can be performed using the same operations, but result is integers.

            SymbMath uses the "short-circuit" definition of AND and OR when the arguments are Boolean.  Here are tables that show how AND and OR are defined:

 

                        a and b

--------------------------------------------------------

                        b          1          0

            a

            1                      1          0

            0                      0          0

------------------------------------------------------

 

                        a or b

--------------------------------------------------------

                        b          1          0

            a

            1                      1          1

            0                      1          0

------------------------------------------------------

 

            Short-circuit evaluation is used because often one condition must be tested before another is meaningful.

            The result of Boolean expression with logic operators is either 1 or 0. Boolean expression like (1 < 3 or 1 > 4) return a real value 1 or 0.  Numeric expressions can replace Boolean ones, provided they evaluate to 1 or 0.  The advantage here is that you can define the step function that is 0 for x < a and 1 for x > a by entering:

 

                        step(x_, a_) := x > a

 

            To define the function:

                                    f(x) = x-1          if x < 1

                                         = x^2-x        if x >= 1

 

            enter:

            f(x_) := (x-1)*(x < 1) + (x^2-x)*(x >= 1)

 

            These functions can be differentiated and integrated symbolically.

 

 

17.2.2.  Function Calls

 

            A function call activates the function specified by the function name. The function call must have a list of actual parameters if the corresponding function declaration contains a list of formal parameters. Each parameter takes the place of the corresponding formal parameter. If the function is external, the function call will automatically load the library specified by its function name plus extension  when needed.

            Some examples of the function calls follow:

            sin(x)               # load the library sin when needed

            integrate(x^2, x)           # load the library int when needed

 

 

17.3.    Statements

17.3.1.  Comment Statements

 

            # is the comment statement sign.

            You can add comments into a line, or even produce a single line which is entirely a comment, by preceding the comment sign with #.

 

            For example:

                        # This is my program;

                        3 + 4    # My first calculation;

 

            Comments make your calculations more understandable, whether you are making a printed record of what you are doing or if you just want to jot some notes to yourself while you are working.

 

 

17.3.2.  Evaluation Statements

 

            The evaluation statement has the format:

 

                        expression

 

            SymbMath evaluates any expression which in a line and gives the value of the expression. e.g.

 

IN:  3 + 4

OUT: 7                         # the value of 3+4

 

IN:  d(x^6, x)

OUT: 6 x^5                   # the value of d(x^6, x)

 

IN:  subs(last, x = 1)     # evaluate the last output when x = 1.

OUT: 6

 

            The last output can be saved to a variable for the later use by the built-in variable "last", e.g. f :=last.

 

 

17.3.3.  Assignment Statements

 

            The assignment in SymbMath language is similar to assignment in such language as PASCAL.

            An assignment operator is   :=

            The assignment statement specifies that a new value of expr2 be assigned to expr1, and saved into memory. The form of the assignment statements is

 

                        expr1 := expr2;

 

            You can use assignment for storing result.

            You can assign the result of calculation or any formula to a variable with a command like:    X := SIN(4.2).

            The assignments are useful for long calculations.  You can save yourself a lot of recalculations by always storing the results of your calculations in your own variables instead of leaving them in the default variable last.

             You can destroy the assignment to X with the command clear(X). If X stored a large list, you could regain a considerable amount of memory by clearing X. Also, since a variable and a function can have the same name, you can clear a variable p, not a function p(x).

            The assignment operator is also used in the definition of a function or procedure.

            Variables can be used in function definitions, and that leads to an important difference between functions and variables.  When a variable is defined, all terms of the definition are evaluated.  When a function is defined, its terms are not evaluated; they are evaluated when the function is evaluated.  That means that if a component of the function definition is changed, that change will be reflected the next time the function is evaluated.

 

            e.g.

IN:  p:=2+3                   # 2+3 is evaluated at the time of assignment, p is assigned with 5.

OUT: p := 5

 

IN:  p(x):=2+3               # 2+3 is evaluated when the value of p(x) is requested, 

                                    # p(x) is assigned with 2+3.

OUT: p(x) := 2+3

 

            If the left hand side of the assignment is a variable, it is the immediate assignment (i.e. expr2 is evaluated at the time of assignment); if the left hand side is a function, it is the delayed assignment (i.e. expr2 is evaluated when the value of expr1 is requested).

            You can force all the components of a function to be evaluated when the function is defined by preceding the function with the command eval():

                        f(x_) := eval(2+3)   # f(x_) is assigned with 5

            Note that not only a variable but also any expression can be assigned. e.g. x := 2, sin(x)/cos(x) := tan(x), a>0 := 1.

            Clear a variable, function or expression from assignment by

 

                        clear(x)            # clear x from assignment.

                        clear(f(x))         # clear f(x) from assignment.

                        clear(a>0)         # clear a>0 from assume(a>0).

 

 

17.3.4.  Conditional

 

            There are two conditional functions:

                        If(test , x)

                        If(test , x , y)

 

            If(condition ,  x) gives x if condition evaluates to 1, or no output otherwise.

            If(condition ,  x ,  y) gives x if condition evaluates to 1, y if it evaluates to 0, or no output if it evaluates to neither 1 or 0. The 2 words (then and else) can be replaced by comma ,.

            It is useful in definition of the use-defined function to left the function unevaluated if the argument of the function is not number. e.g. define f(x_) := If(isnumber(x), 1), then call f(x), f(10) gives 1, and f(a) gives f(a).

 

 

17.3.5.  Loop

 

            You can use two kinds of loops in SymbMath, fixed length loops controlled by do() and variable-length loops controlled by repeat(). The do() loop is similar to the FOR loop in BASIC language.

            The control variable in the do() loops is not limited to integer values. You can say:

 

                        do(f:=f+1, x from xmin to xmax step dx)

 

            It is similar to

                        FOR x := xmin TO xmax STEP dx

                        f:=f+1

                        NEXT x

where xmin, xmax, and dx are real values.  If STEP dx is omitted, it defaults to 1.

 

            e.g.

IN:  x:=0

OUT: x := 0

IN:  do(x:=x+1, j from 1 to 5 step 1)

OUT: x := 5

 

              The conditional loops are probably more useful than the do() loops if a number of iteration is unknown. It is

                        repeat(y until test)

                        repeat(y, test)

            The word (until) can be replaced by comma ,. The repeat() repeats to evaluate f until the test is true (i.e. the result of the test is 1).

 

            Example:

IN:  x:=1

OUT: x := 1

 

IN:  repeat(x:=x+1 until x>5)

OUT: x := 6

 

 

17.3.6.  Switch

 

            The switch sets or changes the switch status. The switch status is unchanged in memory until the switch is assigned by the new value.

 

---------------------------------------------------------------------------------------------------------

Switch                          Action

 

output := math              output form is math symbol notation, this is default.

output := basic              output form is BASIC format.

output := fortran                        output form is FORTRAN format.

output := prolog            output form is PROLOG format (internal form).

output := off                  not display output.

output := on                  the same as output := basic

 

lowercase := on                        convert letters into the lower-case letters.

lowercase := off                        not convert letters into the lower-case letters, this is default.

numeric := on               convert numbers to floating-point numbers.

numeric := off               not convert numbers to floating-point numbers, this is default.

 

expand := on                 expansion. e.g. c*(a+b) to c*a+c*b.

expand := off                disable expansion, this is default.

 

expandexp := on           expand exponent. e.g. c^(a+b) to c^a*c^b.

expandexp := off           disable exponent expansion, this is default.

------------------------------------------------------------------------------------------------------------------

 

 

17.3.6.1.  Output Switch

 

            When the switch output := math, the output displays the math symbol notation.

            When the switch output := basic, the output form is the BASIC language format.

            When the switch output := fortran, the output form is the FORTRAN language format.

            The default switch is output := math.

            The output switch only changes the output format, neither affects the internal format nor the calculation.

 

 

17.3.6.2.  Case Switch

 

            When the switch lowercase := on, all letters are converted into the lower-case letters so the upper- and lower- case letters are the same, e.g. EXP(x) is the same as exp(x).

 

 

17.3.6.3.  Numeric Switch

 

            Example:

IN:  1/2

OUT: ½

 

IN:  numeric := on

IN:  1/2

OUT: 0.5

 

 

17.3.6.4.  Expand Switch

 

            Example:

IN:  a*(b+c)

OUT: a (b + c)

 

IN:  expand := on

IN:  a*(b+c)

OUT: a* b + a* c

 

 

17.3.6.5.  ExpandExp Switch

 

            Example:

IN:  exp(a+b)

OUT: e^(a + b)

 

IN:  expandexp := on

IN:  exp(a+b)

OUT: e^a* e^b

 

17.3.7.  Read and Write Statements

 

            The format of the readfile statement is

                        readfile("filename")

            The filename is any MS-DOS file name. If the file is not in the current directory, the filename should include the directory. e.g.

                        readfile("directory\filename")

            e.g. read a file named "int.sm":

                        readfile("int.sm")

            It seems to copy the file into the user program.

            After a file is read, you can call any part of this package from a second package, as it seems the part of the first program has already been in the second program. you can read many files into the SymbMath program at a time. However, all names of the variables are public and name conflicts must be avoided.

            Write a file to disk by

                        openfile("file")

                        do something

                        closefile("file")

                       

            Table 17.3.7.         Reading and Writing Statements

---------------------------------------------------------------------

readchar                       read a character from  keyboard.

readline                                    read a line of strings from keyboard.

readfile("file")                read (run or include) the file named "file".

 

......................................................................

openfile("file")               open the disk file "file" for writing.

closedfile("file")             closed the file "file".

writes(s)                       write s on screen, only on graphics mode.

newline                         write next text on a new line.

null                               not write.

block(a,b)                     write the value of the last argument, b.

---------------------------------------------------------------------

where the filename is any MS-DOS filename.

 

            Note that the file must be closed by the closefile() command when writing a file with the openfile() command, but the file is automatically closed after reading the file. There must be the end statement at the end of file for reading.

            SymbMath can read expressions from a disk file, then manipulate the expression, and finally write the result into another disk file.

            Example: an expression y:=x^6 is already in the file "y.in",

            The contents of the file "y.in":

---------------------------------------------------------------------

y:=x^6

-----------------------------------------------------------------------

 

            Run this SymbMath program

----------------------------------------------------------------------------

readfile("y.in")               # read the expression y:=x^6 from the file "y.in"

openfile("y.out")                        # open a disk file "y.out" for writing

d(y,x)                           # differentiate y and write the result to the file

closefile("y.out")           # close the file and return output to SymbMath

----------------------------------------------------------------------------

 

            The contents of the file "y.out":

---------------------------------------------------------------------

6*x^5

---------------------------------------------------------------------

 

            In this way you can interface to other software (see 3.7. Interface with Other Software).

            These outputs in the disk file can be edited in the Edit window or the Aux Edit window.

            It is recommended to use the BASIC output format by setting the switch output := basic when you write the output into the disk file. The default switch is output := math.

 

 

17.3.8.  DOS Command

 

            You can executes a DOS command in SymbMath language by

                        system("dir")

 

 

17.3.9.  Sequence Statements

 

            The all above statements are simple statements. The sequence statement specifies that its component statements are to be executed in the same sequence as they are written. They are separated by the separators (comma ","). e.g.

                        a+b, 2+3

 

 

17.4.  Libraries and Packages

 

            A library is a file of an external function, which filename is its function name within 8 letters plus extension . e.g. the library named sin is a file of the sin(x) function definition.

            The library (the * file) is similar to the MS-DOS *.BAT file. You do not need to load or read the library by any command. SymbMath automatically load the library when it is needed. For example, when you use the sin(x) function first time, the library sin will be auto-loaded. The library must be in the default directory, otherwise the library is not loaded and the function is not working. Only the assignments in the library can be loaded, and others in the library will be omitted, but all of these assignments will be not evaluated when they are loaded. You can clear the library sin from memory by clear(sin(x)).

            You can have libraries (external functions) as many as your disk space available. You should use the "one function per file" convenience.

            Note that all names of the variables in libraries and packages are public (global) except for those declared by local() and name conflicts must be avoided.

 

            A package is the SymbMath program file which filename has not  extension . It is recommended that its filename has the extension .SM.

            A package is similar to a library, but the package must be read by a command

                        readfile("filename")

            The filename can be any MS-DOS filename. It is recommended that the filename is same function name used in your program, plus the extension .sm. e.g. int.sm is the filename of the integral package as the name of integral function is integrate(). If the file is not in the current directory, the filename should include the directory. e.g.

                         readfile("directory\filename")

            After reading the package, you can call the commands in the package from your program.

            The readfile() command must be in a single line anywhere.

            Many packages can be read at a time.

            You can convert a package of f.sm into a library by renaming f.sm to f for auto loading, or a library f to a package by renaming f to f.sm for not auto loading.

            You can get help for all libraries by the library Index command in the Help menu. You first open the library index window by this command, then open a library by selecting its library name in the library index window.

            There are many libraries and packages. The following are some of them.

 

 

                        Table 17.4.1      Libraries

------------------------------------------------------------------------

File Name                     Function

 

plot                               plotting functions.

d                                  derivatives.

int                                integrals.

sin                                sin(x) function.

cos                               cos(x) function.

fac                               n!.

sign                              sign(x) function.

abs                               abs(x) function.

arg                               arg(x) function.

sum                              sum function.

NInte                            numeric integration.

NSolve             numeric solver of equation.

DSolve             differential equation solver.

gamma             gamma function.

ei                                 exponential integral function.

series                           Taylor series.

partSum                       partial sum.

infSum              infinite sum.

sinh                              sinh(x) function.

cosh                             cosh(x) function.

average                        average([x]) function.

listSum             sum of list of data.

react                            chemical reactions database.

phoneNo                       phone No. database.

------------------------------------------------------------------------

 

 

                        Table 17.4.2     Packages

------------------------------------------------------------------------

init.sm                          initial package when running the program in

                                    the Input window. It contains switches on the default status.

 

chemical.sm                 the atomic weight of chemical elements.

ExpandTr.sm                expansion of trig functions.

expandLn.sm                expand ln(x*y).

ExpandGa.sm               expand gamma(n,x).

ExpandEi.sm                expand ei(n,x).

units.sm                       an units conversion.

listPlot.sm                    plotting a list of data.

plotData.sm                  interfacing software PlotData.

-----------------------------------------------------------------------

 

 

17.4.1.  Initial Package init.sm

 

            When a program is run in the Input window, SymbMath first automatically reads (or runs) the initial package "init.sm". The commands in the "init.sm" package seems to be the SymbMath system commands. You can read other packages (e.g. f.sm) in the initial package "init.sm", so the commands in the package "f.sm" seems to be in SymbMath system. You do this by adding the readfile("f.sm") into the init.sm file:

                        readfile("f.sm")

 

 

17.4.2.  ExpandLn Package

 

            The lnexpand.sm package does the logarithmic expansion. e.g. ln(a*b) is expanded into ln(a)+ ln(b).

 

                                   

17.4.3.  Chemical Calculation Package

 

            SymbMath recognises 100 symbols of chemical elements and converts them into their atomic weights after the chemical package of "Chemical.sm" is read.

 

            Example:

            Calculate the weight percentage of the element C in the molecule CH4.

 

IN:  readfile("chemical.sm")

IN:  numeric := on

IN:  C/(C+H*4)*100*%

OUT: 74.868 %

 

            Example:

            Calculate the molar concentration of CuO when 3 gram of CuO is in 0.5 litre of a solution.

 

IN:  readfile("chemical.sm")

IN:  numeric := on

IN:  g:=1/(Cu+O)*mol

IN:  3*g/(0.5*l)

OUT: 0.07543 mol/l

 

 

17.5.  Interface with Other Software

 

            You can run SymbMath from another software as a engine. Anthoer software sends a text file to SymbMath, then run SymbMath in background, get result back from SymbMath.

Interface with other software, (e.g. CurFit, Lotus 123) is similar to interface with the software PlotData in the plotdata package "plotdata.sm".

            After load the file "plotdata.sm", the functions

                        plotdata(y, x)

                        plotdata(y, x from xmin to xmax)

                        plotdata(y, x from xmin to xmax step dx)

plot a function of y by mean of the software PlotData. The plotdata() first opens a file "SymbMath.Out" for writing, then write the data table of the y function into the file "SymbMath.Out", then close the file, and finally call the software PlotData to plot. These are done automatically by plotdata(). After it exits from PlotData, it automatically return to SymbMath.

            When SymbMath is interfaced with the software PlotData, SymbMath produces the data table of functions, and PlotData plots from the table. So SymbMath seems to plot the function. This interface can be used to solve equations graphically.

           

            Example:

plot x^2 by interfacing software PlotData.

 

IN:  readfile("plotdata.sm")

IN:  plotdata(x^2, x)

 

in the software PlotData, you just select the option to read the file "SymbMath.Out" and to plot. PlotData reads the data in the SymbMath format without any modification (and in many data format).

            In PlotData,

in the main menu:

1 <Enter>

in the read menu:

2 <Enter>

<Enter>

in the main menu:

2 <Enter>

in the graph menu:

1 <Enter>

 

where <Enter> is the <Enter> key. Refer to PlotData for detail.

 

18.   Graphics

 

            SymbMath includes extensive facilities for graphing. It supports BGI graphics, which graphics commands are the same as those in Borland Turbo Pascal and Turbo C, except for:

 

            different graphics commands

---------------------------------------------------------------

SymbMath                    Turbo Pascal or C

 

graph                           initgraph(drive,mode,path)

text                              closegraph

writes(x)                       outtext(x)

-----------------------------------------------------------------

 

            Note that if your monitor is Hercules, you must load the MSHERC.COM program as a TRS program before you run PlotData. Otherwise you will get Error when you plot.                                     

            Before graphing (drawing or plotting), you must initialize the graphics system and puts the computer hardware into graphics mode by the command:

                        graph

 

 

18.1.  Drawing Lines and Arcs

 

then you can draw a line by

                        line(x1,y1,x2,y2)

                        lineto(x2,y2)

                        linerel(dx,dy)

 

draw a circular arc by               

                        arc(x,y,angle1,angle2,radius)

 

draw an elliptical arc by               

                        ellipse(x,y,angle1,angle2,XRadius,YRadius)

 

put a pixel by                

                        putpixel(x,y,color)

            you can move a pointer by

                        moveto(x,y)

                        moverel(dx,dy)

            A upper left corner on your graphics screen coordinates is (0,0).

            The style of the line can be set by

 

                        setlinestyle()

 

            You can set screen colors. If you are using a color system, you can set the color of the next line or graph or text with the command:

                        setcolor(color)

where color is color number (i.e. an integer in the range 0..15), or one  of the colorno(x) function value.

            You can set the background color for your graphs with the command

                        setbkcolor(color)

where color is color number (i.e. an integer in the range 0..15), or one  of the colorno(x) function value.

 

        Table 18.1     ColorNo(x) function in the colorno library

--------------------------------------------------------------------------------------

x                                  value

 

black                            0

blue                              1

green                           2

cyan                             3

red                               4

magenta                       5

brown                           6

lightgray                       7

gray                             8

lightblue                       9

lightgreen                     10

lightcyan                      11

lightred                         12

lightmagenta                 13

yellow                           14

white                            15

-----------------------------------------------------------------------

 

            You can set line styles.

            On both monochrome and color systems, you can draw lines and graphs with different line styles.  (Since the line segments used to draw graphs are usually very short, different line styles may not be distinguished in graphs, but they will be distinguished on long lines.)  Linestyles are indicated by integers in the range 0..3, and are set by the command:

                        setlinestyle(style,u,thickness)

where style, u and thickness are integers.

            You can set the text style by

                        settextstyle(font,direction,size)

where font, direction and size are integers.

            You can add labels to your graphs by

                        writes(s)

            You can put alphanumeric labels anywhere on your graphic screens. They can be horizontal or vertical, and they can be printed in various sizes. To print a string  s  horizontally on the screen with the lower-left corner at the screen coordinates (x,y), use two commands:

                        moveto(x,y), writes(s)

To write vertically bottom to top, use two commands:

                        settextstyle(1,2,2), writes(s)

             

            If SymbMath attempts to graph a point (x,y) which is outside the the screen coordinate, it ignores the point and continues.  No error message is generated, and even functions which are undefined on part of the graphing domain can be graphed.

            You can get the max x and max y on your graphics screen

coordinates by

                        getmaxx

                        getmaxy

            You can get the current point(x, y) on your graphics screen coordinates by

                        getx

                        gety

            You can get the background color and foregroud color on your graphics screen by

                        getbkcolor

                        getcolor

            You can read a character from the keyboard or pause by the command:

                        readchar

            You can clear graph by

                        cleardevice

 

            SymbMath auto goes back the text mode at the end of run. You can force it goes back the text mode by the command:

                        text

 

            Example:     

#          drawing a group of circles and ovals.

#          Circles are 9 planets around sun.

 

graph                                       # graph mode

do(circle(getmaxx*0.5+2.5*x,getmaxy*0.5,5), x,0,90,10)

do(oval(getmaxx*0.5,getmaxy*0.5,2.5*x,x), x,10,90,10)

readchar                                   # pause graph by read a char

text                                          # back text mode

 

 

18.2.  Plotting f(x)

 

            You can plot a function of y = f(x) on the xy-plane by external function:

 

                        plot(f(x),x)

                        plot(f(x),x,xmin,xmax)

                        plot(f(x),x,xmin,xmax,ymin,ymax)

                        plot(f(x),x,xmin,xmax,ymin,ymax,color)

 

f(x) can be either a function  with bound variable x or an expression involving x.  For example, you could graph the parabola with the command plot(x^2,x). 

            The xmin and xmax are range of x-axis, the ymin and ymax are range of y-axis. The default values are xmin=-5, xmax=5, ymin=-5, and ymax=5. The values of xmin, xmax, ymin, ymax are real numbers, such that  xmin < xmax  and  ymin < ymax.  Thses values tell SymbMath that the visible screen corresponds to a portion of the xy-plane with  xmin <= x <= xmax  and  ymin <= y <= ymax.

            The operator plot() plots one point (x,f(x)) for each pixel on the x-axis, and connects successive points.  To omit the connections and just plot the points, use the command:

                                    dotplot(f(x),x)

            To plot only every 20th point, which is useful for rapidly graphing complicated functions, use

                                    sketch(f(x),x)

            If you want your circles and squares to look correct --that is, if you want one vertical unit to be really the same distance as one horizontal unit--you should select window parameters so that the horizontal axis is 1.4 times as long as the vertical axis.

 

            Example 5.2:               

            plot x^3 and sin(x).

IN:  graph

IN:  plot(x^3,x)               

IN:  plot(sin(x),x)

 

                

18.3.  Plotting Parametric Functions x(t) and y(t)

 

            You can plot the parametric functions of x=x(t) and y=y(t) by

 

                        paraplot(x(t),y(t),t)

                        paraplot(x(t),y(t),t,tmin,tmax)

                        paraplot(x(t),y(t),t,tmin,tmax,ymin,ymax)

 

            Example:

IN:  graph

IN:  paraplot(sin(t),sin(2*t),t)

 

 

18.4.    Plotting f(t) in Polar Coordinates

 

            You can graph the portion of a polar curve  r = f(t) that lies in the window with external function:

 

                       polaplot(f(t),t)

                       polaplot(r, t,tmin,tmax)

                       polaplot(r, t,tmin,tmax,rmin,rmax)

 

f(t) can be a function with bound variable t or an expression involving t.

 

            Example:

            Plot a circle  r = 1 in polar coordinates.

IN:  graph

IN:  polaplot(1,t)

 

The variable t covers the domain (0, 2*pi); you can change this default by specifying a range for t:

                       polaplot(1, t,0,pi)

 

           

18.5.  Plotting Data

 

            You can plot data by

 

                        dataplot([x1,x2,...], [y1,y2,...])

                        dataplot([x1,x2,...], [y1,y2,...], xmin,max)

                        dataplot([x1,x2,...], [y1,y2,...], xmin,xmax,ymin,ymax)

                        dataplot([x1,x2,...], [y1,y2,...], xmin,xmax,ymin,ymax,link)

 

            Example:

IN:  graph

IN:  dataplot([1,2,3], [1,4,9])

 

        You can plot a list of data by

               listplot([y1,y2,...])

for x1=1, x2=2, x3=3, ....

 

            Example:

IN:  graph

IN:  listplot([1,4,9])

 

            You can fit a set of data into a function x^2

            Example 5.7.

IN:  graph

IN:  dataplot([1,2,3,4],[1,4,9,16],0,5,0,20)

IN:  plot(x^2,x,0,5,0,20)

 

 

 

18.6.     Printing Graphics on Printer

 

1. Load the Graphics.EXE file into memory in the DOS prompt by

            c:\DOS\graphics

2. Run SymbMath, then display a graph on screen.

3. Print Screen by pressing the <Print Screen> key on keyboard.

 

Note that you must load the Graphics.EXE file before you run SymbMath.

 

 


Part 3 Reference Guide

 

19.  SymbMath Environment: Windows and Menus

 

            SymbMath is a multi-windowed editor in which you can copy-and-paste anywhere in a file and between files, even from the Help window.

            When you start SymbMath, the computer screen looks like:

 

-----------------------------------------------------------------------------------------

| File  Input  Run  Output  Color                 Help  Example Keyword  |

---------------------------------- Input -----------------------------------------------

|                                                                                                       |

|                                                                                                       |

|                                                                                                       |