Thursday, February 16, 2017

Arithmetic Expressions

My Linux Learning Path

Do Linux to learn Linux.

  1. Define a variable (var1) equal to 3.141516 and print var1.
  2. Define var2=10*var1. Print var2.
  3. Define var3=var1+var2. Print var3.
  4. Define a script and use parameter arguments (two float numbers only) and print:
    • Increase by 0.98 the first value.
    • Increase by one previous result.
    • Increase by 18.0123 the second value.
    • Decrease by one previous result.
    • Addition.
    • Subtraction.
    • Multiplication.
    • Division.
    • Modulo.
    • First value raised to the second value.
  5. Repeat previous exercise but this time assign the result to a fictitious variable. Use parameter expansion to create the variables.
  6. Double parenthesis (arithmetic expansion) deals only with integers. In terminal solve the following:
    • Define var3=12
    • Define var4=31
    • Print var3 + var4.
    • Print var3 - var4.
    • Increase by 1 and print var3
    • Decrease by 1 and print var4
  7. Create a script that ask user to insert tow integer numbers (only) and perform previous operations.
  8. Explain how the following works:
    • Want to get 5.
      (( var1=$1 ))
      (( var2=$2 ))
      
      (( var1 ++ ))
      (( var2 -- ))
      
      echo "Var1 + Var2 is: $(( var1 + var2 )) 
      
    • If var1=2 and var2=2 then result is:
      #!/bin/bash
      
      echo -e "Define var1: \c"
      read var1
      
      echo -e "Define var2: \c"
      read var2
      
      (( var1+=1 ))
      (( var2=var2+3 ))
      
      echo "Var1 + Var2 : $(( var1 + var2 ))"
      
    • This code calculate the present value of a zero coupon bond. Take this as an example and perform similar scripts to get use to it.
      #!/bin/bash
      
      ERROR_PARAM=3
      
      echo -e "Define Bond Principal: \c"
      read fv # Must be positive
      
      echo -e "Define intereset rate: \c"
      read int  # Must be positive and belongs to (0-1)
      
      echo -e "Define maturity: \c"
      read n  # Must be integer
      
      #Performing test
      if [[ fv -lt 0 ]]; then
              echo "Error: Negative Future Value."
              exit $ERROR_PARAM
      fi
      
      if [[ $(echo "$int < 0.0" | bc -l) -eq 1 ]] || [[ $(echo "$int > 1.0" | bc -l) -eq 1 ]]; then
              echo "Error: Interest range out of bounds."
              exit $ERROR_PARAM
      fi
      
      if [[ n -lt 0 ]]; then
              echo "Error: Negative maturity."
              exit $ERROR_PARAM
      fi
      
      rate=$(echo "(1.0+$int)" | bc -l)
      discount=$(echo "$rate^$n" | bc -l)
      pv=$(echo "scale=4; ( $fv / $discount )" | bc -l)
      
      echo "Bond price is: $pv"
      

No comments:

Post a Comment