# 使用局部函数编写基于脚本的测试

### 创建要测试的 approxSinCos 函数

function [sinA,cosA] = approxSinCos(x) % For a given angle in radians, approximate the sine and cosine of the angle % using Taylor series. sinA = x; cosA = 1; altSign = -1; for n = 3:2:26 sinA = sinA + altSign*(x^n)/factorial(n); cosA = cosA + altSign*(x^(n-1))/factorial(n-1); altSign = -altSign; end 

### 创建测试脚本

%% Test 0rad % Test expected values of 0 [sinApprox,cosApprox] = approxSinCos(0); assertWithAbsTol(sinApprox,0) assertWithRelTol(cosApprox,1) %% Test 2pi % Test expected values of 2pi [sinApprox,cosApprox] = approxSinCos(2*pi); assertWithAbsTol(sinApprox,0) assertWithRelTol(cosApprox,1) %% Test pi over 4 equality % Test sine and cosine of pi/4 are equal [sinApprox,cosApprox] = approxSinCos(pi/4); assertWithRelTol(sinApprox,cosApprox,'sine and cosine should be equal') %% Test matches MATLAB fcn % Test values of 2pi/3 match MATLAB output for the sin and cos functions x = 2*pi/3; [sinApprox,cosApprox] = approxSinCos(x); assertWithRelTol(sinApprox,sin(x),'sin does not match') assertWithRelTol(cosApprox,cos(x),'cos does not match') function assertWithAbsTol(actVal,expVal,varargin) % Helper function to assert equality within an absolute tolerance. % Takes two values and an optional message and compares % them within an absolute tolerance of 1e-6. tol = 1e-6; tf = abs(actVal-expVal) <= tol; assert(tf, varargin{:}); end function assertWithRelTol(actVal,expVal,varargin) % Helper function to assert equality within a relative tolerance. % Takes two values and an optional message and compares % them within a relative tolerance of 0.1%. relTol = 0.001; tf = abs(expVal - actVal) <= relTol.*abs(expVal); assert(tf, varargin{:}); end 

• Test 0rad 用于测试 0 弧度的角的计算值和预期值是否位于绝对容差 1e-6 或相对容差 0.1% 范围内。通常，您应使用绝对容差来比较接近 0 的值。

• Test 2pi 用于测试 弧度的角计算值和预期值在 1e-6 的绝对容差或 0.1% 的相对容差范围内是否相等。

• Test pi over 4 equality 用于测试 的正弦和余弦在 0.1% 的相对容差范围内是否相等。

• Test matches MATLAB fcn 用于测试 的正弦和余弦计算值在 0.1% 的相对容差范围内是否等于 sincos 函数中的值。

### 运行测试

results = runtests('approxSinCosTest'); 
Running approxSinCosTest .... Done approxSinCosTest __________ 

rt = table(results) 
rt = 4x6 table Name Passed Failed Incomplete Duration Details _________________________________________ ______ ______ __________ ________ ____________ {'approxSinCosTest/Test0rad' } true false false 0.43177 {1x1 struct} {'approxSinCosTest/Test2pi' } true false false 0.022397 {1x1 struct} {'approxSinCosTest/TestPiOver4Equality' } true false false 0.023893 {1x1 struct} {'approxSinCosTest/TestMatchesMATLABFcn'} true false false 0.042044 {1x1 struct}