quiz4

#include <iostream>
using namespace std;

int factorial(int x) {
if(x==0) {
return 1; }
else {
return x*factorial(x-1); }
}
long double eulerCal(float precision) {
long double e=0, previous=e;
int n=0;
do {
previous=e;
e=e+1.0/factorial (n);
n=n+1; }
while((e-previous)>precision);
return e;
}

int main() {
long double prec;
cout<<“Give the precision to determinate until wich value the program will run”<<endl;
cin>>prec;
cout<<“The Euler value with precision of:”<<” “<<prec<<” “<<“is: “<<” “<<eulerCal(prec)<<endl;
return 0;
}

Quiz #4

EULER!!!!

esimple

Este es el quiz #4 de este curso de programación, este quiz en específico ha sido en el que mas eh tardado en hacer por que de cierta forma me confundía, a tal punto de que busqué ayuda con compañeros que ya llevaron esta materia y con otros compañeros los cuales están llevando junto conmigo este curso.

El programa te pregunta la precisión con la cual quieres el número euler, mientras mas grande sea el número elegido, mas preciso es el número euler gracias a esto:

e = 1 + frac{1}{1} + frac{1}{1cdot 2} + frac{1}{1cdot 2cdot 3} + cdots

 

Quiz 4

Link GitHub: Quiz #4

 

Euler Aprox.

#TC1017 #QUIZ4

So this quiz was actually kinda challenging, it took me quite some time and a lot of questions to Ken to finally work it out. All noteworthy notes can be found on the picture below.

The factorial function was taken from one of the WSQs we did before, the tricky part was that C++ wasn´t giving me all decimals beacause of a disparity with the function’s types. Ken sorted that out😀

quiz4.PNG

Source Code below [GitHub Link: https://github.com/diegodamy/Quiz4 ]

#include <iostream>
using namespace std;

int factorial (int n){
if (n == 0){
return 1;
} else {
return n*factorial(n-1); //This is an example of recursion, and must be implemented since the formula for the n factorial of any number
} // requires the n-1 factorial of given number
}

long double euler_calc (long double prec)
{
long double euler_sum = 0.0; //It’s better to initialize this variable since we shouldn’t asssume it will start at 0 by default
long double prev_sum; // Sometimes that might work but other times it could return junk memory
int n = 0;

do {

prev_sum = euler_sum;
euler_sum = euler_sum + 1.0/ (factorial(n)); // The “1.0” here is VERY important, otherwise it won´t compile correctly.
n = n+1; // A simple “1” won´t work because C++ will stupidly convert our long double variable into an int one, which we don´t want

} while (euler_sum – prev_sum > prec);

return euler_sum;
}

int main(){

long double precision;

cout << “Please input the value of precision:” << endl;
cin >> precision;

cout << “Result is: ” << euler_calc(precision);
}

—————————————————

Photo Credit: <a href=”https://www.flickr.com/photos/57329804@N00/9984539064/”>spanaut</a&gt; via <a href=”http://compfight.com”>Compfight</a&gt; <a href=”https://creativecommons.org/licenses/by-nc-sa/2.0/”>cc</a&gt;

Quiz 4/Euler

2016-04-05 (2)

 

1+1/factorial.

La siguiente imagen explica los factoriales:

eq0003P

 

Para calcular el factorial de un número -WSQ09- los que lo hicieron sabrán :3 sino, en python ya existe una libreria de matematicas en la que calcula el factorial de un número.

math.factorial(n)

Mm. Como yo no tengo mis WSQ guardados, -acabo de formatear la lap- :l lo hice con esto.  Oh, sorpresa, si lo tengo,

2016-04-05 (3) bueno, igual no lo tengo como una función, sólo quedaría meter todo eso dentro de una funcion (la parte donde calcula el factorial, sin las cosas fancy’s).

Y .. Ahora sí, teniendo lo que ocuparemos, va la explicación de la lógica.

El número de Euler el valor máximo que puede dar es 2.71828 … Con esto sabremos si el programa está bien o no.

La formula es dada por suma de fracciones, en la cual, el numerador siempre va a ser 1 y el denominador es 1, 2, ,3… sucesivamente, pero es el factorial de ese número. Entonces… Si le pedimos al usuario que ingrese la precisión que quiere para calcular el número y nos da un.. 40. nuestra suma deberá ser 1+ 1/1! + 1/2! + 1/3! +…1/40! (el signo significa factorial. eso creo). El resultado será   2.71828…. El número de Euler- :3

La repetición de algo nos lleva a un for, el cual se detendría hasta que llegue a n, que será l número ingresado por el usuario.

2016-04-05 (1)

Y.. ahí esta desde el editor de Notepad++ -aunque no le guste a Ken- quizá no es tan bueno, y por bueno me refiero a interactivo.

For i in range (pre+1)… <- el pre + 1 sería el valor de n+1 , porque con los for comienza en 0. i será el valor que vaya aumentando+1 en cada vuelta, por lo tanto

Continue reading “Quiz 4/Euler”

QUIZ#4

QUIZ4
Este es el metodo de Euler, para calcular el factorial en una serie.

CÓDIGO.

#include <iostream>
using namespace std;

int factorial(int x) {
if(x==0) {
return 1; }
else {
return x*factorial(x-1); }
}
long double eulerCal(float precision) {
long double e=0, previous=e;
int n=0;
do {
previous=e;
e=e+1.0/factorial (n);
n=n+1; }
while((e-previous)>precision);
return e;
}

int main() {
long double prec;
cout<<“Give the precision to determinate until wich value the program will run”<<endl;
cin>>prec;
cout<<“The Euler value with precision of:”<<” “<<prec<<” “<<“is: “<<” “<<eulerCal(prec)<<endl;
return 0;
}

Quiz #4

The instructions: 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).

The Euler number is very important in the math area and we can calculate it with this formula:

e =  displaystylesumlimits_{n = 0}^{ infty} dfrac{1}{n!} = 1 + frac{1}{1} + frac{1}{1cdot 2} + frac{1}{1cdot 2cdot 3} + cdots

Here you can see my code on Atom

quiz4

quiz41

Also you can check here my code on Github

Quiz 4

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:

euler

Let’s start with the code.

euler01

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. euler 02

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

euler 03

Continue reading “Quiz 4”

Quiz 04

  • This quiz was about creating 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.
  • I research about the Euler’s number here because I didn’t know what exactly was it.
  • My code and ran in the terminal
Captura de pantalla 2016-04-07 a las 7.43.37 p.m.
—————–>My code in GitHub<——————

Quiz 04 Euler number

If x  = 5, what is the mass of the sun? escalated.jpg

That same reaction was what I had when I got in charge of doing Quiz 04. This time we had to make the sum of 1 divided by n! factorial. This until it reaches the euler number = 2.71 and it stops looping around.

quiz04.png

I broke my head constantly for several days trying to reach the answer for this equation in python3 language. This was until Ken Bauer miraculously helped me out and teached me what means each step means. I am not trying to pass the course by copy pasting codes. It is just that I have to see what is happening in a code first and then analyse it. This is in order to learn what to do and use it for future references. For instance, from the previous WSQ09 i learned to do factorials, so that was a piece of cake in this quiz. This is the code:

quiz04code

And this is how it runs:

quiz04run

When n! is 18 and n! is 19, the answer it is the same. That moment it is when it stops.

I am going to introduce another David Bowie’s song over here just for one reason, maybe a slowpoke one since I just realized it. This one is called Lazarus. It was released in his most recent album Blackstar in 2016. This song got his video release 3 days before he passed away in January 10th 2016. It is a really sad song. Was he saying goodbye? Who knows, but it gives this song even a bigger meaning. May he rest in peace.

lazarus.png