New FAMILUG

The PyMiers

Monday 10 December 2012

[bash] Dùng bash thay máy tính cầm tay

trước tớ đã có bài viết về dùng python để thay máy tính cầm tay, hôm nay xin thêm 1 bài về dùng bash để tính toán với các số nguyên. Và những điều nay không ở đâu xa lạ cả, ngay trong man bash . Chú ý là chỉ dùng bash để tính toán các phép tính SỐ NGUYÊN:

ta dùng cấu trúc $((biểu thức cần tính))

hvn@lappy: ~ $ echo $((2**62))
4611686018427387904
hvn@lappy: ~ $ echo $((2**63))
-9223372036854775808
hvn@lappy: ~ $ echo $((2**64))
0
hvn@lappy: ~ $ echo $((2**63))
-9223372036854775808
hvn@lappy: ~ $ echo $((15 % 4))
3
hvn@lappy: ~ $ echo $((7 / 4))
1
hvn@lappy: ~ $ echo $((1 + 1))
2
như vậy giá trị lớn nhất bash có thể tính là khoảng 2 mũ 62. Các phép tính chia sẽ làm tròn xuống (floor), phép công trừ, chia lấy dư thực hiện rất nuột nà :v

danh sách các toán tử được ghi đầy đủ trong man bash, tớ trích ra đây 1 đoạn:

ARITHMETIC EVALUATION
       The shell allows arithmetic expressions  to  be  evaluated,  under
       certain  circumstances  (see  the let and declare builtin commands
       and Arithmetic Expansion).   Evaluation  is  done  in  fixed-width
       integers  with  no  check  for  overflow,  though division by 0 is
       trapped and flagged as an error.  The operators and  their  prece‐
       dence,  associativity,  and  values  are the same as in the C lan‐
       guage.  The following list of operators is grouped into levels  of
       equal-precedence  operators.   The  levels  are listed in order of
       decreasing precedence.

       id++ id--
              variable post-increment and post-decrement
       ++id --id
              variable pre-increment and pre-decrement
       - +    unary minus and plus
       ! ~    logical and bitwise negation
       **     exponentiation
       * / %  multiplication, division, remainder
       + -    addition, subtraction
       << >>  left and right bitwise shifts
       <= >= < >
              comparison
       == !=  equality and inequality
       &      bitwise AND
       ^      bitwise exclusive OR
       |      bitwise OR
       &&     logical AND
       ||     logical OR

No comments:

Post a Comment