Sfoglia il codice sorgente

First commit revised public version

Jose Ortiz 9 anni fa
commit
358c756d04

+ 1305
- 0
ArithmeticExpressions-PrettyPlots.html
File diff soppresso perché troppo grande
Vedi File


+ 379
- 0
README.md Vedi File

@@ -0,0 +1,379 @@
1
+[English](#markdown-header-arithmetic-expressions-pretty-plots) | [Español](#markdown-header-expresiones-aritmeticas-grafico-bello)
2
+
3
+#Expresiones aritméticas - Gráficas Bonitas
4
+
5
+
6
+![rsz_heart.png](images/rsz_heart.png)
7
+![rsz_mariposa1.png](images/rsz_mariposa1.png)
8
+![rsz_mariposa.png](images/rsz_mariposa.png)
9
+
10
+Las expresiones aritméticas son parte esencial de casi cualquier algoritmo que resuelve un problema útil.  Por lo tanto,  implementar expresiones aritméticas correctamente es una destreza básica en cualquier lenguaje de programación de computadoras. En esta experiencia de laboratorio practicarás la implementación de expresiones aritméticas en C++ escribiendo  ecuaciones paramétricas para graficar curvas interesantes.
11
+
12
+
13
+
14
+##Objetivos:
15
+
16
+1. Implementar expresiones aritméticas en C++ para producir gráficas. 
17
+2. Utilizar constantes adecuadamente.
18
+3. Definir variables utilizando tipos de datos adecuados.
19
+4. Convertir el valor de un dato a otro tipo cuando sea necesario.
20
+
21
+
22
+##Pre-Lab:
23
+
24
+Antes de llegar al laboratorio debes:
25
+
26
+1. Haber repasado los siguientes conceptos:
27
+
28
+	a. implementar expresiones aritméticas en C++
29
+
30
+	b. tipos de datos nativos de C++ (int, float, double, char)
31
+
32
+	c. usar "type casting" para covertir el valor de una variable a otro tipo dentro de expresiones.
33
+
34
+	d. utilizar funciones y constantes aritméticas de la biblioteca `cmath`
35
+
36
+	e. la ecuación y gráfica de un círculo
37
+
38
+2. Haber estudiado los conceptos e instrucciones para la sesión de laboratorio.
39
+
40
+3. Haber tomado el quiz Pre-Lab que se encuentra en Moodle.
41
+
42
+---
43
+---
44
+
45
+##Ecuaciones paramétricas
46
+
47
+Las *ecuaciones paramétricas* nos permiten representar una cantidad como función de una o más variables independientes llamadas *parámetros*. En muchas ocasiones resulta útil representar curvas utilizando un conjunto de ecuaciones paramétricas que expresen las coordenadas de los puntos de la curva como funciones de los parámetros. Por ejemplo, en tu curso de trigonometría debes haber estudiado que la ecuación de un círculo con radio $r$ y centro en el origen tiene una forma así: 
48
+
49
+$$x^2+y^2=r^2.$$
50
+
51
+
52
+Los puntos $(x,y)$ que satisfacen esta ecuación son los puntos que forman el círculo de radio $r$ y centro en el origen.  Por ejemplo, el círculo con $r=2$ y centro en el origen tiene ecuación
53
+
54
+$$x^2+y^2=4,$$
55
+
56
+y sus puntos son los pares ordenados $(x,y)$ que satisfacen esa ecuación. Una forma paramétrica de expresar las coordenadas de los puntos de el círculo con radio $r$ y centro en el origen es: 
57
+
58
+$$x=r \cos(t)$$
59
+
60
+$$y=r \sin(t),$$
61
+
62
+donde $t$ es un parámetro que corresponde a la medida (en radianes) del ángulo positivo con lado inicial que coincide con la parte positiva del eje de $x$, y lado terminal que contiene el punto $(x,y)$, como se muestra en la Figura 1.
63
+
64
+
65
+---
66
+
67
+![figura1.jpg](images/figura1.jpg)
68
+
69
+<b>Figura 1.</b> Círculo con centro en el origen y radio $r$.
70
+
71
+
72
+
73
+---
74
+
75
+Para graficar una curva que está definida usando ecuaciones paramétricas, computamos los valores de $x$ y $y$ para un conjunto de valores del parámetro. Por ejemplo, para $r = 2$, algunos de los valores son
76
+
77
+---
78
+
79
+| $t$ | $x$ | $y$ |
80
+|-----|-----|-----|
81
+| $0$ | $2$ | $0$ |
82
+| $\frac{\pi}{4}$ | $\frac{\sqrt{2}}{2}$ | $\frac{\sqrt{2}}{2}$ |
83
+| $\frac{\pi}{2}$ | $0$ | $2$ |
84
+
85
+
86
+**Figura 2.** Algunas coordenadas de los puntos $(x,y)$ del círculo con radio $r=2$ y centro en el origen.
87
+
88
+---
89
+---
90
+
91
+##Sesión de laboratorio:
92
+
93
+###Ejercicio 1
94
+
95
+En este ejercicio graficarás algunas ecuaciones paramétricas que generan curvas interesantes. 
96
+
97
+**Instrucciones**
98
+
99
+1.	Carga a Qt el proyecto `prettyPlot`  haciendo doble "click" en el archivo `prettyPlot.pro` que se encuentra en la carpeta `Documents/eip/Expressions-PrettyPlots` de tu computadora. También puedes ir a `http://bitbucket.org/eip-uprrp/expressions-prettyplots` para descargar la carpeta `Expressions-PrettyPlots` a tu computadora.
100
+
101
+2. Configura el proyecto y ejecuta el programa marcando la flecha verde en el menú de la izquierda de la ventana de Qt Creator. El programa debe mostrar una ventana parecida a la Figura 3.
102
+
103
+	---
104
+
105
+	![figura3.png](images/figura3.png)
106
+
107
+	<b>Figura 3.</b> Segmento de línea desplegado por el programa <i>PrettyPlot</i>.
108
+
109
+	---
110
+
111
+3. El archivo `main.cpp` (en Sources) contiene la función `main()` donde estarás añadiendo código. Abre ese archivo y estudia el código. La línea `XYPlotWindow wLine;` crea el objeto `wLine` que será la ventana en donde se dibujará una gráfica, en este caso la gráfica de un segmento. Observa el ciclo `for`. En este ciclo se genera una serie de valores para $t$ y se computa un valor de $x$ y $y$ para cada valor de $t$. Cada par ordenado $(x,y)$  es añadido a la gráfica del segmento por el método `AddPointToGraph(x,y)`. Luego del ciclo se invoca el método `Plot()`, que "dibuja" los puntos, y el método `show()`, que muestra la gráfica. Los *métodos* son funciones que nos permiten trabajar con los datos de los objetos. Nota que cada uno de los métodos se escribe luego de `wLine`, seguido de un punto. En una experiencia de laboratorio posterior aprenderás más sobre objetos y practicarás como crearlos e invocar sus métodos.
112
+
113
+	Las expresiones que tiene tiene tu programa para $x$ y $y$  son ecuaciones paramétricas  para la línea que pasa por el origen y tiene el mismo valor para las  coordenadas en $x$ y $y$. Explica por qué la línea solo va desde 0 hasta aproximadamente 6.
114
+
115
+4.	Ahora escribirás el código necesario para graficar un círculo. La línea `XYPlotWindow wCircle;` crea el objeto `wCircle` para la ventana donde se graficará el círculo. Usando como inspiración el código para graficar el segmento, escribe el código necesario para que tu  programa grafique un círculo de radio 3 con centro en el origen.  Ejecuta tu programa y, si es necesario, modifica el código hasta que obtengas la gráfica correcta. Recuerda que el círculo debe graficarse dentro del objeto `wCircle`. Por esto, al invocar los métodos `AddPointToGraph(x,y)`, `Plot` y `show`, éstos deben ser precedidos por `wCircle`, por ejemplo, `wCircle.show()`.
116
+
117
+5. Tu próxima tarea es graficar una curva cuyas ecuaciones paramétricas son:
118
+
119
+	$$x=16 \sin^3(t)$$
120
+	$$y=13 \cos(t) - 5 \cos(2t) - 2 \cos(3t) - \cos(4t)-3.$$
121
+
122
+
123
+	Si implementas las expresiones correctamente debes ver la imagen de un corazón.  Esta gráfica debe haber sido obtenida dentro de un objeto `XYPlotWindow` llamado `wHeart`.
124
+
125
+6. Ahora graficarás una curva cuyas ecuaciones paramétricas son:
126
+
127
+	$$x=5\cos(t) \left[ \sin^2(1.2t) + \cos^3(6t) \right]$$
128
+	$$y= 10\sin(t) \left[ \sin^2(1.2t) +  \cos^3(6t) \right].$$
129
+
130
+
131
+	Observa que ambas expresiones son casi iguales, excepto que una comienza con $5\cos(t)$ y la otra con $10\sin(t)$. En lugar de realizar el cómputo de $ \sin^2(1.2t) + \cos^3(6t)$ dos veces, puedes asignar su valor a otra variable $q$ y realizar el cómputo así:
132
+
133
+	$$q =  \sin^2(1.2t) + \cos^3(6t)$$
134
+	$$x = 5 \cos(t)(q)$$
135
+	$$y = 10  \sin(t)(q).$$
136
+
137
+	
138
+	Implementa las expresiones de arriba, cambia la condición de terminación del `for` a `t < 16*M_PI` y observa la gráfica que resulta. Se supone que parezca una mariposa. Esta gráfica debe haber sido obtenida dentro de un objeto `XYPlotWindow` llamado `wButterfly`.
139
+
140
+7. Entrega el archivo `main.cpp` que contiene el código con las ecuaciones paramétricas de las gráficas del círculo, el corazón y la mariposa utilizando   "Entrega 1" en Moodle. Recuerda utilizar buenas prácticas de programación, incluir el nombre de los programadores y documentar tu programa.
141
+
142
+En [3] puedes encontrar otras ecuaciones paramétricas de otras curvas interesantes.
143
+
144
+
145
+###Ejercicio 2
146
+
147
+En este ejercicio escribirás un  programa para obtener el promedio de puntos para la nota de un estudiante.
148
+
149
+Supón que todos los cursos en la Universidad de Yauco son de $3$ créditos y que las notas tienen las siguientes puntuaciones: $A = 4$ puntos por crédito; $B = 3$ puntos por crédito; $C = 2$ puntos por crédito; $D = 1$ punto por crédito y $F = 0$ puntos por crédito. 
150
+
151
+**Instrucciones**
152
+
153
+1. Crea un nuevo proyecto "Non-Qt" llamado Promedio. Tu función `main()`  contendrá el código necesario para pedirle al usuario el número de A's, B's, C's, D's y F's obtenidas por el estudiante y computar el promedio de puntos para la nota (GPA por sus siglas en inglés).
154
+
155
+2. Tu código debe definir las constantes $A=4, B=3, C=2, D=1, F=0$ para la puntuación de las notas, y pedirle al usuario que entre los valores para las variables $NumA$, $NumB$, $NumC$, $NumD$, $NumF$. La variable $NumA$ representará el número de cursos en los que el estudiante obtuvo $A$,  $NumB$ representará el número de cursos en los que el estudiante obtuvo $B$, etc. El programa debe desplegar el GPA del estudiante en una escala de 0 a 4 puntos. 
156
+
157
+
158
+
159
+	**Ayudas:** 
160
+
161
+	1. El promedio se obtiene sumando las puntuaciones  correspondientes a las notas obtenidas (por ejemplo, una A en un curso de 3 créditos tiene una puntuación de 12), y dividiendo esa suma por el número total de créditos.
162
+
163
+	2. Recuerda que, en C++, si divides dos números enteros el resultado se "truncará" y será un número entero. Utiliza "type casting": `static_cast\<tipo\>(expresión)' para resolver este problema.
164
+
165
+3. Verifica tu programa calculando el promedio de un estudiante que tenga dos A y dos B; ¿qué nota tendría este estudiante, A o B (la A va desde 3.5 a 4.0)?. Cuando tu programa esté correcto, guarda el archivo `main.cpp` y entrégalo  utilizando  "Entrega 2" en Moodle. Recuerda seguir las instrucciones en el uso de nombres y tipos para las variables,  incluir el nombre de los programadores, documentar tu programa y utilizar buenas prácticas de programación. 
166
+
167
+
168
+
169
+
170
+---
171
+---
172
+
173
+##Referencias:
174
+
175
+[1] http://mathworld.wolfram.com/ParametricEquations.html
176
+
177
+[2] http://paulbourke.net/geometry/butterfly/
178
+
179
+[3] http://en.wikipedia.org/wiki/Parametric_equation
180
+
181
+---
182
+---
183
+---
184
+
185
+[English](#markdown-header-arithmetic-expressions-pretty-plots) | [Español](#markdown-header-expresiones-aritmeticas-grafico-bello)
186
+
187
+#Arithmetic Expressions - Pretty Plots
188
+
189
+![rsz_heart.png](images/rsz_heart.png)
190
+![rsz_mariposa1.png](images/rsz_mariposa1.png)
191
+![rsz_mariposa.png](images/rsz_mariposa.png)
192
+
193
+Arithmetic expressions are an essential part of almost any algorithm that solves a useful problem. Therefore, a basic skill in any computer programming language is to implement arithmetic expressions correctly. In this laboratory experience you will practice the implementation of arithmetic expressions in C++ by writing parametric equations to plot interesting curves.
194
+
195
+##Objectives:
196
+
197
+1. To implement arithmetic expressions in C++ to produce graphs. 
198
+2. To use constants adequately. 
199
+3. To define variables using adequate data types.
200
+4. To cast a data value to another type when necessary.
201
+
202
+
203
+##Pre-Lab:
204
+
205
+Before you get to the laboratory you should have:
206
+
207
+1. Reviewed the following concepts:
208
+
209
+	a. implementing arithmetic expressions in C++.
210
+
211
+	b. native data types in C++ (int, float, double)
212
+
213
+	c. using  "type casting" to cast the value of variables to other data types within expressions.
214
+
215
+	d. using arithmetic functions and constants from the `cmath` library.
216
+
217
+	e. the equation and graph of a circle.
218
+
219
+2. Studied the concepts and instructions for the laboratory session.
220
+
221
+3. Taken the Pre-Lab quiz that can be found in Moodle.
222
+
223
+---
224
+---
225
+
226
+
227
+## Parametric Equations
228
+
229
+*Parametric equations* allow us to represent a quantity as a function of one or more independent variables called *parameters*. In many occasions it is useful to represent curves using a set of parametric equations that express the coordinates of the points of the curve as functions of the parameters. For example, in your trigonometry course you should have studied that the equation of the circle of radius $r$ and centered at the origin has the following form:
230
+
231
+
232
+$$x^2+y^2=r^2.$$
233
+
234
+The points $(x,y)$ that satisfy this equation are the points that form the circle of radius $r$ and center at the origin. For example, the circle with $r=2$ and center at the origin has equation
235
+
236
+
237
+$$x^2+y^2=4,$$
238
+
239
+and its points are the ordered pairs $(x,y)$ that satisfy this equation. A parametric representation of the coordinates of the points in the circle of radius $r$ and center at the origin is:
240
+
241
+
242
+
243
+$$x=r \cos(t)$$
244
+
245
+$$y=r \sin(t),$$
246
+
247
+where $t$ is a parameter that corresponds to the measure (in radians) of the positive angle  with initial side that coincides with the positive part of the $x$-axis and terminal side that contains the point $(x,y)$, as it is illustrated in Figure 1.
248
+
249
+
250
+---
251
+
252
+![figura1.jpg](images/figura1.jpg)
253
+
254
+<b>Figure 1.</b> Circle of radius $r$ and centered at the origin.
255
+
256
+
257
+
258
+---
259
+
260
+To plot a curve that is described  by parametric equations, we compute the $x$ and $y$ values for a set of values of the parameter. For example, for $r=2$, some of the values are
261
+
262
+
263
+---
264
+
265
+| $t$ | $x$ | $y$ |
266
+|-----|-----|-----|
267
+| $0$ | $2$ | $0$ |
268
+| $\frac{\pi}{4}$ | $\frac{\sqrt{2}}{2}$ | $\frac{\sqrt{2}}{2}$ |
269
+| $\frac{\pi}{2}$ | $0$ | $2$ |
270
+
271
+
272
+**Figure 2.** Some of the coordinates of the points $(x,y)$ of the circle of radius $r=2$ and centered at the origin.
273
+
274
+---
275
+---
276
+
277
+##Laboratory session:
278
+
279
+###Exercise 1
280
+
281
+In this exercise you will plot the graphs of some parametric equations of interesting curves.
282
+
283
+**Instructions**
284
+
285
+1. Double click the file `prettyPlot.pro` that is inside the `Documents/eip/Expressions-PrettyPlots` folder to load the project `prettyPlot` into Qt. 
286
+You can also download the folder `Expressions-PrettyPlots` from  `http://bitbucket.org/eip-uprrp/expressions-prettyplots`.
287
+
288
+2. Configure the project and run the program by clicking the green arrow in the menu on the left side of the Qt Creator window. The program should display a window similar to the one in Figure 3.
289
+
290
+	---
291
+
292
+	![figura3.png](images/figura3.png)
293
+
294
+	<b>Figure 3.</b> Line segment displayed by the program <i>PrettyPlot</i>.
295
+
296
+
297
+
298
+	---
299
+
300
+3. The file `main.cpp` (in Sources) contains the function `main()` where you will be adding code. Open this file and study the code. The line  `XYPlotWindow wLine;` creates the object `wLine`, that is the window that will show the plot of a graph, in this case the graph of a segment. Look at the `for` cycle. In this cycle several values for $t$ are generated and a value for $x$ and $y$ is computed for each $t$. Each ordered pair $(x,y)$ is added to the graph of the segment by the method `AddPointToGraph(x,y)`.  After the cycle, there is a call to the  method  `Plot()`, to "draw" the points in the graph, and to the method `show()`, to show the plot. The *methods* are functions that allow us to work with the data of an object. Note that each of the methods is written after `wLine`, and followed by a period. In a later laboratory experience you will learn more about objects and practice how to create them and invoke their methods.
301
+
302
+	The expressions for $x$ and $y$ are parametric equations for the line that passes through the origin and has the same value for $x$ and $y$. Explain why this line only goes from 0 to approximately 6.
303
+
304
+	
305
+
306
+4.	You will now write the code needed to plot a circle. The line `XYPlotWindow wCircle;` creates the object `wCircle`  for the window that will contain the plot of the circle. Using as inspiration the code that plotted the segment, write the necessary code for your program to graph a circle of radius 3 and centered at the origin. Run your program and, if it is necessary, modify the code until you get the right plot. Remember that the circle should be plotted inside the `wCircle` object. Thus, when you invoke the `AddPointToGraph(x,y)`, `Plot` and `show` methods, they should be preceeded by `wCircle`; e.g. `wCircle.show()`.
307
+
308
+
309
+5. Your next task is to plot a curve with the following parametric equations:
310
+
311
+
312
+	$$x=16 \sin^3(t)$$
313
+	$$y=13 \cos(t) - 5 \cos(2t) - 2 \cos(3t) - \cos(4t)-3.$$
314
+
315
+
316
+	If you implement the equations correctly, you will see the image of a heart. This plot should be obtained inside an `XYPlotWindow` object called `wHeart`.
317
+
318
+	
319
+6.  You will now plot the curve of the following parametric equations:
320
+
321
+
322
+	$$x=5\cos(t) \left[ \sin^2(1.2t) + \cos^3(6t) \right]$$
323
+	$$y= 10\sin(t) \left[ \sin^2(1.2t) +  \cos^3(6t) \right].$$
324
+
325
+
326
+	Note that both expressions are almost the same, the only difference is that one starts  with $5\cos(t)$ and the other with $10\sin(t)$. Instead of computing $ \sin^2(1.2t) + \cos^3(6t)$ twice, you can assign its value to another variable $q$ and compute $x$ and $y$ as follows:
327
+
328
+
329
+	$$q =  \sin^2(1.2t) + \cos^3(6t)$$
330
+	$$x = 5 \cos(t)(q)$$
331
+	$$y = 10  \sin(t)(q).$$
332
+
333
+
334
+	Implement the above expressions,  change the condition for termination of the  `for` to   `t < 16*M_PI`, and look at the plot that it is displayed. It should look like a butterfly. This plot should be obtained inside an `XYPlotWindow` object called `wButterfly`.
335
+
336
+7. Use "Deliverable 1" in Moodle to submit the file  `main.cpp` containing the code with the parametric equations for the graphs of the circle, the heart, and the butterfly. Remember to use good programming practices, to include the names of the programmers and to document your program.
337
+
338
+	
339
+
340
+In [3] you can find other parametric equations of interesting curves.
341
+
342
+
343
+
344
+###Exercise 2
345
+
346
+In this exercise you will write a program to obtain a student's grade point average (GPA).
347
+
348
+Suppose that all courses in Cheo's University are 3 credits each and have the following point values: $A = 4$ points per credit; $B = 3$ points per credit; $C = 2$ points per credit; $D = 1$ point per credit y $F = 0$ points per credit. 
349
+
350
+**Instructions**
351
+
352
+1. Start a new "Non-Qt" project called "Average". Your `main()` function will contain the necessary code to ask the user for the number of A's, B's, C's, D's and F's obtained and compute the grade point average (GPA).
353
+
354
+2. Your code should define the constants  $A=4, B=3, C=2, D=1, F=0$ for the points per credit, and ask the user to input the values for the variables  $NumA$, $NumB$, $NumC$, $NumD$, $NumF$. The variable $NumA$ represents the number of courses in which the student obtained A, $NumB$ represents the number of courses in which the student obtained B, etc. The program should display the GPA using the 0-4 point scale.
355
+
356
+	**Hints:** 
357
+
358
+	1. You can obtain the GPA by adding the credit points corresponding to the grades (for example, an A in a 3 credit course has a value of 12 points), and dividing this sum by the total number of credits.
359
+
360
+
361
+	2. Remember that, in C++, when both operands in the division are integers, the result will also be an integer; the remainder will be discarded. Use "type casting": `static_cast\<type\>(expression)' to solve this problem.
362
+
363
+3. Verify your program by computing the GPA of a student that has two A's and 2 B's; what is the grade of this student, A or B (A goes from 3.5 to 4 points)? When your program is correct, save the `main.cpp` file and submit it using "Deliverable 2" in Moodle. Remember to follow the instructions regarding the names and types of the variables,  to include the names of the programmers, to document your program and to use good programming practices.
364
+
365
+
366
+
367
+
368
+
369
+---
370
+---
371
+
372
+##References:
373
+
374
+[1] http://mathworld.wolfram.com/ParametricEquations.html
375
+
376
+[2] http://paulbourke.net/geometry/butterfly/
377
+
378
+[3] http://en.wikipedia.org/wiki/Parametric_equation
379
+

BIN
images/Figura3.png Vedi File


BIN
images/figura1.jpg Vedi File


BIN
images/main1.png Vedi File


BIN
images/rsz_heart.png Vedi File


BIN
images/rsz_mariposa.png Vedi File


BIN
images/rsz_mariposa1.png Vedi File


+ 54
- 0
main.cpp Vedi File

@@ -0,0 +1,54 @@
1
+/* Ive modifico el programa en Junio 3 para anadir ventanas para el circulo, el corazon, y la mariposa */
2
+
3
+
4
+#include "xyplotwindow.h"
5
+#include <QApplication>
6
+
7
+int main(int argc, char *argv[])
8
+{
9
+    QApplication a(argc, argv);
10
+    XYPlotWindow wLine;
11
+    XYPlotWindow wCircle;
12
+    XYPlotWindow wHeart;
13
+    XYPlotWindow wButterfly;
14
+    
15
+    double y = 0.00;
16
+    double x = 0.00;
17
+    double increment = 0.01;
18
+    
19
+    // Plot of a segment
20
+    
21
+    for (double t = 0; t < 2*M_PI; t = t + increment) {
22
+        
23
+        x = t;
24
+        y = t;
25
+        
26
+        // add x and y as a point in the graph
27
+        wLine.AddPointToGraph(x,y);
28
+    }
29
+    
30
+    // After all the points have been added, plot and show the graph
31
+    wLine.Plot();
32
+    wLine.show();
33
+    
34
+    
35
+    
36
+    // Plot of a circle
37
+    
38
+    
39
+    // YOUR CODE FOR THE CIRCLE HERE
40
+    
41
+    
42
+    // Plot of a heart
43
+    
44
+    
45
+    // YOUR CODE FOR THE HEART HERE
46
+    
47
+    
48
+    // Plot of a butterfly
49
+    
50
+    
51
+    // YOUR CODE FOR THE BUTTERFLY HERE
52
+    
53
+    return a.exec();
54
+}

+ 26
- 0
prettyPlot.pro Vedi File

@@ -0,0 +1,26 @@
1
+#-------------------------------------------------
2
+#
3
+# Project created by QtCreator 2014-02-26T09:55:52
4
+#
5
+#-------------------------------------------------
6
+
7
+QT       += core gui
8
+
9
+greaterThan(QT_MAJOR_VERSION, 4): QT += widgets printsupport
10
+
11
+TARGET = prettyPlot
12
+TEMPLATE = app
13
+
14
+
15
+SOURCES += main.cpp\
16
+    qcustomplot.cpp \
17
+    xyplotwindow.cpp
18
+
19
+HEADERS  += \
20
+    qcustomplot.h \
21
+    xyplotwindow.h
22
+
23
+FORMS    += \
24
+    xyplotwindow.ui
25
+
26
+OTHER_FILES +=

+ 21370
- 0
qcustomplot.cpp
File diff soppresso perché troppo grande
Vedi File


+ 3529
- 0
qcustomplot.h
File diff soppresso perché troppo grande
Vedi File


+ 37
- 0
xyplotwindow.cpp Vedi File

@@ -0,0 +1,37 @@
1
+#include "xyplotwindow.h"
2
+#include "ui_xyplotwindow.h"
3
+#include "qcustomplot.h"
4
+#include <cmath>
5
+
6
+XYPlotWindow::XYPlotWindow(QWidget *parent) :
7
+    QMainWindow(parent),
8
+    ui(new Ui::XYPlotWindow)
9
+{
10
+    ui->setupUi(this);
11
+}
12
+
13
+
14
+// Añade la x y y a sus respectivos vectores.
15
+void XYPlotWindow::AddPointToGraph(double x, double y) {
16
+        XX.push_back(x);
17
+        YY.push_back(y);
18
+}
19
+
20
+// Esta función invoca los métodos apropiados de customPlot para que
21
+// se grafiquen los puntos.
22
+void XYPlotWindow::Plot() {
23
+    ui->customPlot->xAxis->setLabel("x");
24
+    ui->customPlot->yAxis->setLabel("y");
25
+    ui->customPlot->xAxis->setRange(-25.0, 25.0);
26
+    ui->customPlot->yAxis->setRange(-25.0, 25.0);
27
+    
28
+    QCPCurve *myCurve =  new QCPCurve(ui->customPlot->xAxis, ui->customPlot->yAxis);
29
+    ui->customPlot->addPlottable(myCurve);
30
+    myCurve->setData(XX,YY);
31
+}
32
+
33
+XYPlotWindow::~XYPlotWindow()
34
+{
35
+    delete ui;
36
+}
37
+

+ 29
- 0
xyplotwindow.h Vedi File

@@ -0,0 +1,29 @@
1
+#ifndef MAINWINDOW_H
2
+#define MAINWINDOW_H
3
+
4
+#include <QMainWindow>
5
+#include "qcustomplot.h"
6
+
7
+namespace Ui {
8
+class XYPlotWindow;
9
+}
10
+
11
+class XYPlotWindow : public QMainWindow
12
+{
13
+    Q_OBJECT
14
+
15
+public:
16
+    explicit XYPlotWindow(QWidget *parent = 0);
17
+    //void setupgraph();
18
+    ~XYPlotWindow();
19
+    void AddPointToGraph(double x, double y);
20
+    void Plot();
21
+
22
+
23
+private:
24
+    Ui::XYPlotWindow *ui;
25
+    QVector<double> XX, YY;
26
+    QVector<double> XXN, YYN;    
27
+};
28
+
29
+#endif // MAINWINDOW_H

+ 59
- 0
xyplotwindow.ui Vedi File

@@ -0,0 +1,59 @@
1
+<?xml version="1.0" encoding="UTF-8"?>
2
+<ui version="4.0">
3
+ <class>XYPlotWindow</class>
4
+ <widget class="QMainWindow" name="XYPlotWindow">
5
+  <property name="geometry">
6
+   <rect>
7
+    <x>0</x>
8
+    <y>0</y>
9
+    <width>754</width>
10
+    <height>633</height>
11
+   </rect>
12
+  </property>
13
+  <property name="windowTitle">
14
+   <string>XYPlotWindow</string>
15
+  </property>
16
+  <widget class="QWidget" name="centralWidget">
17
+   <widget class="QCustomPlot" name="customPlot" native="true">
18
+    <property name="geometry">
19
+     <rect>
20
+      <x>0</x>
21
+      <y>0</y>
22
+      <width>691</width>
23
+      <height>581</height>
24
+     </rect>
25
+    </property>
26
+   </widget>
27
+  </widget>
28
+  <widget class="QMenuBar" name="menuBar">
29
+   <property name="geometry">
30
+    <rect>
31
+     <x>0</x>
32
+     <y>0</y>
33
+     <width>754</width>
34
+     <height>22</height>
35
+    </rect>
36
+   </property>
37
+  </widget>
38
+  <widget class="QToolBar" name="mainToolBar">
39
+   <attribute name="toolBarArea">
40
+    <enum>TopToolBarArea</enum>
41
+   </attribute>
42
+   <attribute name="toolBarBreak">
43
+    <bool>false</bool>
44
+   </attribute>
45
+  </widget>
46
+  <widget class="QStatusBar" name="statusBar"/>
47
+ </widget>
48
+ <layoutdefault spacing="6" margin="11"/>
49
+ <customwidgets>
50
+  <customwidget>
51
+   <class>QCustomPlot</class>
52
+   <extends>QWidget</extends>
53
+   <header>qcustomplot.h</header>
54
+   <container>1</container>
55
+  </customwidget>
56
+ </customwidgets>
57
+ <resources/>
58
+ <connections/>
59
+</ui>