《NumPy Beginner's Guide》笔记Chapter8

时间:2023-02-09 14:24:38
# -*- coding: utf-8 -*-
import numpy as np
__author__ = 'ZengDong'
#日期 = 15:04
""" Some programmers test only in production. If you are not one of them you're probably familiar with the concept of unit testing. Unit tests are automated tests written by a programmer to test his or her code. These tests could, for example, test a function or part of a function in isolation. Only a small unit of code is tested by each test. The benefits are increased confidence in the quality of the code, reproducible tests, and as a side effect, more clear code. Python has good support for unit testing. Additionally, NumPy adds the numpy. testing package to that for NumPy code unit testing. """

""" 【Assert functions】 For integers, comparison is a trivial operation, but for floating-point numbers it is not because of the inexact representation by computers. The numpy.testing package has a number of utility functions that test whether a precondition is true or not, taking into account the problem of floating-point comparisons: 函数: assert_almost_equal Raises an exception if two numbers are not equal up to a specified precision assert_approx_equal Raises an exception if two numbers are not equal up to a certain significance assert_array_almost_equal Raises an exception if two arrays are not equal up to a specified precision assert_array_equal Raises an exception if two arrays are not equal assert_array_less Raises an exception if two arrays do not have the same shape and the elements of the first array are strictly less than the elements of the second array assert_equal Raises an exception if two objects are not equal assert_raises Fails if a specified exception is not raised by a callable invoked with defined arguments assert_warns Fails if a specified warning is not thrown assert_string_equal Asserts that two strings are equal assert_allclose Raise an assertion if two objects are not equal up to desired tolerance """


""" 1. assert_almost_equal """


#Imagine that you have two numbers that are almost equal. Let's use the assert_almost_ equal function to check whether they are equal
#call the function with low precision
print("Decimal 6", np.testing.assert_almost_equal(0.123456789, 0.123456780, decimal=7))#输出:Decimal 6 None 因为没有exception

#call the function with higher precision(8diecmal)
#print("Decimal 7", np.testing.assert_almost_equal(0.123456789, 0.123456780, decimal=8)) #输出:raise AssertionError(_build_err_msg())


""" 2. Approximately equal arrays abs(actual - expected) >= 10**-(significant - 1) """
#The assert_approx_equal function raises an exception if two numbers are not equal up to a certain number of significant digits.

print("Significance 8", np.testing.assert_approx_equal(0.123456789, 0.123456780, significant=8)) #输出:('Significance 8', None)

#significance 9 : exception


""" 3. Almost equal arrays assert_array_almost_equal:raises an exception if two arrays are not equal up to a specified precision. |expected - actual| < 0.5 10-decimal """
print("Decimal 8", np.testing.assert_array_almost_equal([0, 0.123456789], [0, 0.123456780], decimal=8))


""" 4. Equal arrays assert_array_equal: raises an exception if two arrays are not equal The shapes of the arrays have to be equal and the elements of each array must be equal. """
print("Pass", np.testing.assert_allclose([0, 0.123456789, np.nan], [0, 0.123456780, np.nan], rtol=1e-7, atol=0))

#assert_array_equal Fail


""" 5. Ordering arrays The assert_array_less function raises an exception if two arrays do not have the same shape and the elements of the first array are strictly less than the elements of the second array. """
print("Pass", np.testing.assert_array_less([0, 0.123456789, np.nan], [1, 0.23456780, np.nan]))  #Pass None



""" 6. Objects comparison The assert_equal function raises an exception if two objects are not equal. The objects do not have to be NumPy arrays, they can also be lists, tuples, or dictionaries. """




""" 7. String comparison The assert_string_equal function asserts that two strings are equal. 大小写敏感 """

print("Pass", np.testing.assert_string_equal("Numpy", "Numpy"))



print("888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888")
""" 8. Floating point comparisons The representation of floating-point numbers in computers is not exact. This leads to issues when comparing floating-point numbers. The assert_array_almost_equal_nulp and assert_array_max_ulp NumPy functions provide consistent floating-point comparisons. """
#Let's see the assert_array_almost_equal_nulp function in action:
#determine the machine epsilon with the finfo function
eps = np.finfo(float).eps
print("EPS", eps)   #输出:('EPS', 2.2204460492503131e-16)

#Compare two almost equal floats: Compare 1.0 with 1 + epsilon (eps) using the assert_almost_equal_nulp function
print("1", np.testing.assert_array_almost_equal_nulp(1.0, 1.0 + eps))
#print("2", np.testing.assert_array_almost_equal_nulp(1.0, 1.0 + 2*eps))






print("99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999")
""" 9. Unit tests Unit tests are automated tests, which test a small piece of code, usually a function or method. """
#we start by writing the factorial function
def factorial(n):
    if n == 0:
        return 1
    if n < 0:
        raise ValueError, "Unexcepted negative value"
    return np.arange(1, n+1).cumprod()





#now we will write the unit test, Let's write a class that will contain the unit tests.
#It's extends the TestCase class from the unittest module which is part of standard Python
import unittest
class FactorialTest(unittest.TestCase):
    def test_factorial(self):
    #Test for the factorial of 3 that should pass.
        self.assertEqual(6, factorial(3)[-1])
        np.testing.assert_equal(np.array([1, 2, 6]), factorial(3))

    def test_zero(self):
    #Test for the factorial of 0 that should pass
        self.assertEqual(1, factorial(0))

    def test_negative(self):
        #Test for the factorial of negative numbers that should fail
        #It should throw a ValueError, but we expect IndexError
        self.assertRaises(IndexError, factorial(-10))

    if __name__ == "__main__":
        unittest.main()





print("10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 ")
""" 10. Nose tests decorators numpy.testing.decorators.deprecated Filters deprecation warnings when running tests. numpy.testing.decorators.knownfailureif Raises KnownFailureTest exception based on a condition. numpy.testing.decorators.setastest Marks a function as being a test or not being a test. numpy.testing.decorators.skipif Raises SkipTest exception based on a condition. numpy.testing.decorators.slow Labels test functions or methods as slow. """