Sie sind auf Seite 1von 1

Name _____________________________

ChBE 2120, Numerical Methods, Paravastu Section, Fall 2018


Quiz 1
1) (5 points) The following function is meant to test whether or not a list of numbers contains only zeros, but
Anant screwed it up. The input list L is assumed to contain at least one number. Correct the mistakes in this
MATLAB function.
function [ ZeroList ] = TestIfZeroList( L )
%Input: L is a list of numbers of any length greater than or equal to 1.
%Output: ZeroList will be 1 if L contains only zeros and 0 otherwise.
if L(1) ~= 0 %~= means NOT EQUAL
ZeroList = 1;
elseif length(L) > 2
ZeroList = TestIfZeroList(L(2:end));
else
ZeroList = 1;
end
end

2) (5 points) There is a simpler way to accomplish what TestIfZeroList does in Problem 1 above. Write a new function
to accomplish the task in the following 3 steps:
Step 1: Square every number in L. The resultant list can only contain positive numbers and zeros.
Step 2: Add up every number in this new list. To do this, you may use MATLAB’s built-in “sum”
function.
Step 3: If the resultant sum is greater than 0, then there must have been at least one nonzero element in L.
Implement Steps 1-3, starting with the function header below.

function [ ZeroList ] = TestIfZeroList( L )


%Input: L is a list of numbers of any length greater than 1.
%Output: ZeroList will be 1 if L contains only zeros and 0 otherwise.

end

3. (5 points) What is the output to the following function call, for the (incorrect) function BisectionMethod below? Note
that by default MATLAB’s sin function works in radians, not degrees.
>> [xllist, xulist] = BisectionMethod(@(x)sin(x), 3, 3)

function [ xllist, xulist] = BisectionMethod ( f, xl, xu)


xllist = 1:0.5:2;
xulist = 1:2;
for i = 1:2
xr = (xu+xl)/2;
if f(xl)*f(xr) < 0
xu = xr;
elseif f(xl)*f(xr) > 0
xl = xr;
else
xu = xr;
xl = xr;
end
xulist(i) = xu;
xllist(i) = xl;
end
end

Das könnte Ihnen auch gefallen