Hello everyone, quiz 4 will be about this:
“Create a function called euler_calc with a single parameter precision. The value of precision is used to determine when to stop calculating. Your calculation will stop when the two consecutive values estimating e differ by less than precision (remember to use absolute value when calculating the difference between two values here)”
First of all, we need to know what the euler number is. According with the internet’s messiah, Wikipedia, “The number e is an important mathematical constant that is the base of the natural logarithm. It is approximately equal to 2.71828,and is the limit of (1 + 1/n)n as n approaches infinity, an expression that arises in the study of compound interest. It can also be calculated as the sum of the infinite series”
The following image describes the formula:
Let’s start with the code.
In line 3, I’m defining the function with the variable (pre) that means ‘precision’, which will be the parameter of precision that the code will allow.
Then, let’s proceed with the math: I’ll explain form line 7 and then we’ll see why the ‘x’, ‘e’, and ‘dif’ variables are defined like that.
Ok, line 6 says that as long as the difference is bigger than the precision, our code will keep running. Then, we add a new value: ‘e_viejo’ to assign the las value that ‘e’ had, (We ought to be conscious that 2 euler variable are needed so we can compare their values and decide if it matches with the ‘precision’ ok?)
As expected, we need to import ‘factorial’ form the ‘math’ library. I’ll add that in line 1.
Aaaand we make the operations in line 9. Line 10 will increase the value of ‘x’ as the While loop gets executed over and over again. To finish the loop, we define the value of ‘dif’ so the condition can be evaluated.
As I told you, now I’ll explain line 4, 5 and 6. The ‘x’ and ‘e’ variables need to have a ‘0’ value before they get into the loop. And it’s REALLY important that the ‘dif’ variable has a bigger number than ‘pre’ because if not, the code won’t run.
Now let’s prove the function.
YAAAAY it worked.
Here’s my code, have fun with it. See you later…!