灌输一些观念

check

  • identity check(证同性测试)

    如C++面向对象设计时的赋值构造(assignment constructor)要避免自我赋值

    Widget& Widget::operator=(const Widget& rhs)
    {
        if (this == &rhs) return *this;
                                // identity test
        ....
    }
  • sanity check(合理性检测)

    有时为避免出错,需做一些简单的甚至傻瓜式的检验。

    import numpy as np
    
    np.random.seed(0)
    
    p = np.random.random(100000)
    
    rolls = np.random.random((11, len(p)))
    
    Alice_wins = np.cumsum(rolls < p, 0)
    Bob_wins = np.cumsum(rolls >= p, 0)
    
    total_wins = Alice_wins + Bob_wins
    assert np.all(total_wins.T == np.arange(1, 12))
                                        # sanity check,
                                        # == array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
    print('sanity check passed')
                        # 方案之二
                        # Alice_wins = rolls < p
                        # Bob_wins = rolls >= p
                        # total_wins = Alice_wins + Bob_wins
                        # assert np.all(total_wins == 1)
                        # print('sanity check passed')

如何在程序中实现概率机制

一大法宝:if条件判断,例 P(A)=p,P(B)=1p

if (x<p)
{           // x ~ U[0, 1]
            // 表达事件A发生的概念。
    ...
}
else
{
            // 表达事件B发生的概念
    ...
}
p = np.random.random(100000)
rolls = np.random.random((11, len(p)))
Alice_wins = np.cumsum(rolls < p, 0)
Bob_wins = np.cumsum(rolls >= p, 0)
            # 如果 p = 0.6
            # 则 Alice_wins == .6,Bob_wins == .4



你可能感兴趣的:(灌输一些观念)