Question: Python3: Returns the value of (e ** x) to within the given margin of error. def exp(x,err=1e-6): Returns the value of (e ** x)

Python3: Returns the value of (e ** x) to within the given margin of error.

def exp(x,err=1e-6): """ Returns the value of (e ** x) to within the given margin of error. Do NOT return (math.E ** x). This function is more precise than that answer. The value (e ** x) is given by the Power Series 1 + x + (x ** 2)/2 + (x ** 3)/3! + ... + (x ** n)/ n! + ... We cannot add up infinite values in a program. So we APPROXIMATE (e ** x) by choosing a value n and stopping at that: 1 + x + (x ** 2)/2 + (x ** 3)/3! + ... + (x ** n)/ n! The error of this approximation is abs( (x ** (n+1))/(n+1)!) which we want less than err. So to compute e ** x, we just keep computing term = (x ** n)/ n! in a loop until this value is less than our error. If it is not less than the error, we add it to the accumulator, which we return at the end. Hint: (x**(n+1))/(n+1)! == (x**n)/n! * x/(n+1) Use this fact to simplify your loop. Parameter x: the exponent for e ** x Precondition: x is a numbers Parameter err: The margin of error (OPTIONAL: default is e-6) Precondition: err > 0 is a number """

------------------------------------------------

Test Cases Below

import func

def test_exp(): """ Tests procedure for function exp(). """ print('Testing exp()') # Note that we round the result to ignore anything outside margin of error result = round(func.exp(1),5) introcs.assert_floats_equal(2.71828, result) result = round(func.exp(1,1e-12),11) introcs.assert_floats_equal(2.71828182846, result) result = round(func.exp(-2),5) introcs.assert_floats_equal(0.13534, result) result = round(func.exp(-2,1e-12),11) introcs.assert_floats_equal(0.13533528324, result) result = round(func.exp(8,1e-1),0) introcs.assert_floats_equal(2981.0, result) result = round(func.exp(8),5) introcs.assert_floats_equal(2980.95799, result) result = round(func.exp(8),11) introcs.assert_floats_equal(2980.95798664543, result)

if __name__ == '__main__': test_exp() print('Module func passed all tests.')

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!