User Tools

Site Tools


gibson:teaching:spring-2018:math445:lecture:arithmetic

Math 445 Mathematics and Applications in Matlab

Four goals

  1. learn numerical programming
  2. learn applied mathematics
  3. explore applications
  4. think about science and society
  5. grow in speaking, writing, reading, maturity

Command line (REPL)

  • Read an expression
  • Evaluate it
  • Print the result
  • Loop back –do it again!

example

>> 4 + 5 
ans
  = 9
>>

Arithmetic operators

  +  plus  
  -  minus
  *  times
  /  divide
  \  divide
  ^  power
  %  comment

examples

>> 4^3
ans
  = 64
 
>> 4/3
ans
  = 1.33333
 
>> 4\3
ans
  = 0.75
 
>> 4+3  % write a comment here, Matlab will ignore it
ans
  = 12

Precedence

  ^      first
  * / \  next 
  + -    last

examples

>>  2*5^2-3/4+1
ans
  = 50.25

>> (2*5)^2-3/(4+1)
ans =
   99.4000

Special numbers

pi   3.1415926...
inf  infinity
NaN  not a number
i    imaginary unit
j    imaginary unit for electrical eningeers!
>> 1/0
ans =
   Inf
 
>> 0/0
ans =
   NaN
 
>> i^2
ans =
    -1
 
>> j^2
ans =
    -1
 
>> sin(pi)
ans =
  1.2246e-16  % wha...?

What does this mean? This is scientific notation shorthand: 1.2246e-16 means $1.2246 \times 10^{-16}$. So the answer is nearly zero.

But why is sin(pi) not exactly zero? Because computers can store and compute only finite truncations of real numbers. Matlab can't represent $\pi$ exactly, only a truncation of $\pi$ that is accurate to sixteen decimal digits.

>> 0.4 - 0.3 - 0.1
ans =
   2.7756e-17  % wha...?

Here the issue is that computers use binary representations of numbers, not decimal representations. None of the three numbers 0.4, 0.3, and 0.1 can be represented exactly in binary. They're instead represented with binary fractions very nearly equal to 0.4, 0.3, and 0.1. Usually you don't see the difference, but sometimes, like here, you do.

Variables

>> x = 4  % assign value of 4 to variable x
x = 
  4
 
>> y = 3 % assign value of 3 to variable x
y = 
  3
 
>> x*y   % evaluate x times y
ans =
  12
 
>> ans   % variable ans is value of last expression
ans =
  12

Evaluating expressions

If you want to evalue the same expression repeatedly with different variables, reset the value of the variables and use the arrow keys to “scroll up” to the expression. Then hit “enter”

>> x = 3;
>> y = x^2 - 2*x + 5
y =
    8
 
>> x = 1; 
>> y = x^2 - 2*x + 5  
y =
    4

basic math functions

  sin, cos, tan, sec, csc, cot, asin, acos, atan          % the classic trig funcs, in radians
  sind, cosd, tand, secd, cscd, cotd, asind, acosd, atand % the classic trig funcs, in degrees
  exp, log, log10, abs, sqrt, factorial, mod              % other awesome functions

Workspace commands

help
; supress

format compact
format loose
format long
format short
diary on
diary off
who
whos 
clear x
clear all
ls or dir
pwd
cd 
gibson/teaching/spring-2018/math445/lecture/arithmetic.txt · Last modified: 2018/01/24 18:05 by gibson