科學運算-矩陣 (一)

運行環境

  1. 安裝 numpy 套件
  2. 安裝 SciPy 套件

程式碼

import numpy as np

a = np.array([1, 2, 3], float)
b = np.array([5, 2, 6], float)


def Print(msg, ans):
    print msg,
    print ans


def PrintFloat(msg, ans):
    print msg,
    print '%.2f' % ans


def Sum():
    ans = (a + b).sum()
    PrintFloat('sum(a + b) = ', ans)


def Mean():
    ans = (a + b).mean()
    PrintFloat('mean(a + b) = ', ans)


def StdDev():
    ans = (a + b).std()
    PrintFloat('std(a + b) = ', ans)


def Add():
    ans = a + b
    Print('a + b = ', ans)


def Minus():
    ans = a - b
    Print('a - b = ', ans)


def Multiply():
    ans = a * b
    Print('a * b = ', ans)


def Devide():
    ans = b / a
    Print('b / a = ', ans)


def Mod():
    ans = a % b
    Print('a % b = ', ans)


def Power():
    ans = b ** a
    Print('b ** a = ', ans)


def Main():
    Sum()
    Mean()
    StdDev()

    print

    Add()
    Minus()
    Multiply()
    Devide()
    Mod()
    Power()


if __name__ == "__main__":
    Main()

執行結果

sum(a + b) =  19.00
mean(a + b) =  6.33
std(a + b) =  2.05

a + b =  [ 6.  4.  9.]
a - b =  [-4.  0. -3.]
a * b =  [  5.   4.  18.]
b / a =  [ 5.  1.  2.]
a % b =  [ 1.  0.  3.]
b ** a =  [   5.    4.  216.]
ċ
numpy-arr-math.py
(1k)
李智,
2015年3月8日 下午9:09