Sunday, June 29, 2014

awk: numeric functions

1. Mathematical Functions
script_1:
 #! /bin/bash  
   
 awk 'BEGIN {  
   print atan2(90, 1); # arctangent of 90/1  
   print cos(90); # cosine of 90  
   print exp(10); # exponential of 10  
   print int(10.23); # integer part of 10.23  
   print log(10); # natural logrithm of 10  
   print sin(90); # return the sine of 90  
   print sqrt(5); # return the square root of 5  
   
 #output:  
 #1.55969  
 #-0.448074  
 #22026.5  
 #10  
 #2.30259  
 #0.893997  
 #2.23607  
 }'  

2. Random Number
Without srand(), rand() will return the same set of random numbers for each process.
rand() returns the random number from [0,1)
script_1:
 #! /bin/bash  
   
 awk 'BEGIN {  
   for(i=0; i<3; i++)  
   {  
     print rand();  
   }  
 }  
 '  
   
 #output:  
 #0.411633  
 #0.322733  
 #0.179324  
   
 awk 'BEGIN {  
   for(i=0; i<3; i++)  
   {  
     print rand();  
   }  
 }  
 '  
   
 #output:  
 #0.411633  
 #0.322733  
 #0.179324  
========================================
script_1:
srand() could setup the seed which make rand() return different set of random numbers every time.

 #! /bin/bash  
   
 awk 'BEGIN {  
   srand(); #If not providing the seed number as parameter  
        #By default it will use the current time stamp  
   for(i=0; i<3; i++)  
   {  
     print rand();  
   }  
 }  
 '  
   
 #output:  
 #0.582961  
 #0.827199  
 #0.736815  
   
 awk 'BEGIN {  
   srand(999);  
   for(i=0; i<3; i++)  
   {  
     print rand();  
   }  
 }  
 '  
   
 #output:  
 #0.537788  
 #0.605322  
 #0.650132  
   

No comments:

Post a Comment