JMathLabTutorial:Programming

From jWork.ORG
Revision as of 20:37, 27 December 2016 by Jworkorg (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search
Limitted access. Reguest membership or login to this link first if you are already a member
Contents


Programming

Programs can be created and run interactively. Functions can be either built-in or user defined.

Branches

Branches can be defined as in any language:

if test1
    code1;
else 
    code2;
end;

"if x A else B end"

As an example a function with the if statement


function y = H2(f, e)
  if (f==1)
    y = e+f;
  else
    y = e+2*f;
  end
end
y= H2(1,2)
printf('%f\n',y)
y=H2(2,2)
printf('%f',y)

Loops

Loops with condition x and statement(s) A: while x A end The while-loop is repeated until x becomes false (0).


x=1;y=1;
while(x<10) y=x+y; x++; end
printf('%f',y)

Loops with counter z and statement(s) A:

"for z = vector A end"

In the for-loop the counter is formally initialized by a vector. In each execution of the loop the counter takes on the value of the next element of vector.


x=1;y=1;
for(x=1:0.1:100) y=x^2+y; end
printf('%f',y)

Jumps

return, continue, break

A function may be part of the loop, and begins another cycle. break permanently leaves the loop.


x=1;
while( 1 ) 
    if(x>1000) 
       break; 
    end 
    x++; 
end
printf('%f',x)

Summary

Definition Example
Branch
if x==0 xp=1; end
if x==0 xp=1; else xp=2; end
Loop
while x<17 x=x+1; end
for i=0:100 x=x+i; end
Jump
return, continue, break
Function
function y=ttwo(x) y=2*x; end
Evaluate
eval('x=24')
Text output
printf('Number=%f', x)
Error message
error('Test')


Benchmarking

You can benchmark your code to ensure that your code is optimized. Here is a small example to see how fast jMathLab is:


a1=time(0)
x=0
n=0
for i=0:1000000 
     x=x+cos(i)*sin(i)*sqrt(i*10); 
     n=n+1;
     end
printf('%f\n',x)
a2=time(0)
printf('iterations=%f\n',n)
printf('processed for %f (sec)',(a2-a1)/1000)

Here "time(0)" return the number of milliseconds since 1970. Run this code and compare with any other similar code.

Let us compare performance of 2 codes: one is written in jMathLab and one in Jython/Python. Here what we have:


d1=time(0) 
s=1;
n=0
for(x=0:1:1000000) 
        s=s+cos(x)*sin(x^2);
       n=n+1;
end
d2=time(0);
printf('\nNr of iterations=%f\n',n) ;
printf('Time=%f',(d2-d1)/1000)

No let's rewrite the same program in Jython:


import math
import time
start = time.clock()
n=0
s=0
for x in range(1000000):
     s=s+math.cos(x)*math.sin(x*x)
     n=n+1
print ' CPU time (s)=',time.clock()-start

The output of each of these scripts will give you ideas about the performance of Jython and jMathlab