Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
restrepo
GitHub Repository: restrepo/ComputationalMethods
Path: blob/master/exams/Taller_2018_2_01_1007790895.ipynb
934 views
Kernel: Python 3 (ipykernel)

Ejercicio 1

El siguiente url entrega 1000 artículos (ver/work?rows=100 al final del url) de la revista con el ISSN: 1029-8479 correspondiente a "Journal of High Energy Physics" en formato JSON usando el API de CrossRef:

https://api.crossref.org/journals/1029-8479/works?rows=100

La base de datos con los 100 artículos que tambíen se puede cargar en otro DataFrame de Pandas, se encuentra anidada en la celda con fila 'items' y columna 'messages' la cual se puede obtener con el método .loc['items','message'] del DataFrame original.

Obtenga la lista de DOIs para los artículos de Alessandro Strumia en esa base de datos

Ejercicio 2

2a):

Genere un polinomio de numpy con 7 raices aleatorias entre 1 y 10, es decir p(x)=(xx0)(xx1)(xx6), p(x)=(x-x_0)\cdot(x-x_1)\cdots(x-x_6), donde (x0,x1,x6)(x_0,x_1,\ldots x_6) son números aleatorios entre 1 y 10.

2b)

Encuentre los puntos críticos del polinomio: las raices de la derivada el polinomio.

2c)

Con alguno de los métodos para encontrar mínimos compruebe que el punto crítico con menor (mayor) valor para el polinomio, corresponde al mínimo (máximo) global del polinomio en el rango de 1 a 10.

2d)

Grafique el polinomío incluyendo los puntos criticos.

Solución

Ejercicio 1

import pandas as pd
issn='1029-8479' items=100 crf='https://api.crossref.org'
url='{}/journals/{}/works?rows={}'.format( crf,issn,items) url
'https://api.crossref.org/journals/1029-8479/works?rows=100'
df=pd.read_json(url) df

La base de datos anindad en fila 'items y columna 'message' es una lista de diccionarios, de modo que se puede cargar como otro DataFrame para facilitar su visualización y análisis

dff=pd.DataFrame( df.loc['items','message'] )
dff[:1]

La columna author contiene los datos requeridos

f='Alessandro' l='Strumia' dfa=dff[( dff['author'].astype(str).str.contains(l) & dff['author'].astype(str).str.contains(f) )] dfa

La lista de DOIS del autor Alessadro Strumia es:

dfa.DOI.to_list()
['10.1088/1126-6708/2000/12/016', '10.1088/1126-6708/2001/11/048']

Ejercicio 2

%pylab inline
import numpy as np from scipy import optimize

2a)

p=np.poly1d( np.random.uniform(1,10,7),r=True )

2b)

Puntos críticos del polinomio

c=p.deriv().roots c
array([6.91790009, 6.80594061, 5.37413449, 3.78324784, 2.57176337, 1.77628349])

con valores para el polinomio dados por

p(c)
array([-1.17187979e-01, 4.65088766e-02, -9.04079489e+01, 4.07851836e+01, -4.33575441e+01, 2.44378403e+01])

2c)

xmin=c[p(c).argsort()[0]] xmin
5.374134490214993

Compruebe el mínimo global

optimize.minimize(p,xmin,bounds=((1,10),))['x']
array([5.37413447])

Compruebe el máximo global

xmax=c[p(c).argsort()[-1]] xmax
3.783247842609016
optimize.minimize(-p,xmax,bounds=((1,10),))['x']
array([3.78324786])

2d)

x=np.linspace(1,10,100) plt.plot(x,p(x),'k-') plt.plot(c,p(c),'ro') plt.plot(xmin,p(xmin),'y*',markersize=15) plt.plot(xmax,p(xmax),'y*',markersize=15) plt.ylim(p(c).min()-100,p(c).max()+100) plt.xlim(c.min()-1,c.max()+1) plt.xlabel('$x$') plt.ylabel('$p(x)$') plt.grid()
Image in a Jupyter notebook

Ejercicio

Un vehículo parte del reposo en un punto con una aceleración constante de a1a_1. 10 segundos después pasa por el mismo punto, y en la misma dirección, un segundo vehículo con una rapidez de 10 m/s y con aceleración constante a2a_2. Calcule el punto de encuentro:

  1. Gráficamente

  2. Encontrando las raíces del polinomio generado a partir de igualar las dos ecuaciones de movimiento.

  3. Grafique el polinomio generado

Ayuda: La ecuación de movimiento para el movimiento uniformemente acelerado es: x=x0+v0(tt0)+12a(tt0)2,\begin{align} x=x_0+v_0 (t-t_0)+\tfrac{1}{2} a (t-t_0)^2\,, \end{align} donde

  • x0x_0 es la posición inicial

  • v0v_0 es la rapidez inicial

  • t0t_0 es el tiempo inicial

Ejecute la siguiente celda para fijar los valores de las aceleraciones en su caso

%pylab inline import numpy as np a1=np.random.choice([2,3,4,5,6]) a2=a1+4 print('a1={} m/s² and a2={} m/s²'.format(a1,a2))
Populating the interactive namespace from numpy and matplotlib a1=5 m/s² and a2=9 m/s²
from scipy import optimize

Se establecen las condiciones iniciales y se definen las ecuaciones de movimiento

x0=0 #Posición inicial para 1 y 2 v0=10 #Velocidad inicial de 2 t0=10 #Tiempo inicial de 2 x1 = lambda t: x0+0.5*a1*t**2 x2 = lambda t: x0+v0*(t-t0)+0.5*a2*(t-t0)**2

1. Gráficamente

plt.xlabel('Tiempo [s]', size=13) plt.ylabel('Posición [m]', size=13)
t = np.linspace(0,50,100) plt.plot(t,x1(t), 'k', label="Vehiculo 1", linewidth=2) plt.plot(t,x2(t), 'c', label="Vehiculo 2", linewidth=2) plt.legend() plt.vlines(35,0,x1(t).max(), 'mediumslateblue', linestyles='--') plt.hlines(x1(35),0,t.max(), 'mediumslateblue', linestyles='--') plt.xlabel('Tiempo [s]', size=13) plt.ylabel('Posición [m]', size=13) plt.xlim(0,50) plt.ylim(0,x1(50)) plt.grid()
Image in a Jupyter notebook

Gráficamente el punto de encuentro se da aproximadamente cuando t = 35 s a más de 3000 m

2. Hallando las raíces del polinomio

Se define le polinomio y se hallan sus raíces con el método de Newton

x = lambda t: x1(t)-x2(t) tf=optimize.newton(x,30) #Encuentra la raiz utilizando el metodo de Newton tf
35.0
print('El punto de encuentro es en x = {} m cuando t = {} s'.format(x1(tf),tf))
El punto de encuentro es en x = 3062.5 m cuando t = 35.0 s

3. Graficando el polinomio

plt.plot(t,x(t), 'lightcoral', linewidth=2) plt.xlabel('Tiempo [s]', size = 13) plt.ylabel('$x_1(t)-x_2(t)$ [m]', size = 13) plt.xlim(0,50) plt.grid()
Image in a Jupyter notebook

Así, se ve que después de t =10s el polinomio x1(t)x2(t)x_1(t)-x_2(t) es 0 cuando t = 35s

import numpy as np
np.sort?
Signature: np.sort(a, axis=-1, kind=None, order=None) Docstring: Return a sorted copy of an array. Parameters ---------- a : array_like Array to be sorted. axis : int or None, optional Axis along which to sort. If None, the array is flattened before sorting. The default is -1, which sorts along the last axis. kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, optional Sorting algorithm. The default is 'quicksort'. Note that both 'stable' and 'mergesort' use timsort or radix sort under the covers and, in general, the actual implementation will vary with data type. The 'mergesort' option is retained for backwards compatibility. .. versionchanged:: 1.15.0. The 'stable' option was added. order : str or list of str, optional When `a` is an array with fields defined, this argument specifies which fields to compare first, second, etc. A single field can be specified as a string, and not all fields need be specified, but unspecified fields will still be used, in the order in which they come up in the dtype, to break ties. Returns ------- sorted_array : ndarray Array of the same type and shape as `a`. See Also -------- ndarray.sort : Method to sort an array in-place. argsort : Indirect sort. lexsort : Indirect stable sort on multiple keys. searchsorted : Find elements in a sorted array. partition : Partial sort. Notes ----- The various sorting algorithms are characterized by their average speed, worst case performance, work space size, and whether they are stable. A stable sort keeps items with the same key in the same relative order. The four algorithms implemented in NumPy have the following properties: =========== ======= ============= ============ ======== kind speed worst case work space stable =========== ======= ============= ============ ======== 'quicksort' 1 O(n^2) 0 no 'heapsort' 3 O(n*log(n)) 0 no 'mergesort' 2 O(n*log(n)) ~n/2 yes 'timsort' 2 O(n*log(n)) ~n/2 yes =========== ======= ============= ============ ======== .. note:: The datatype determines which of 'mergesort' or 'timsort' is actually used, even if 'mergesort' is specified. User selection at a finer scale is not currently available. All the sort algorithms make temporary copies of the data when sorting along any but the last axis. Consequently, sorting along the last axis is faster and uses less space than sorting along any other axis. The sort order for complex numbers is lexicographic. If both the real and imaginary parts are non-nan then the order is determined by the real parts except when they are equal, in which case the order is determined by the imaginary parts. Previous to numpy 1.4.0 sorting real and complex arrays containing nan values led to undefined behaviour. In numpy versions >= 1.4.0 nan values are sorted to the end. The extended sort order is: * Real: [R, nan] * Complex: [R + Rj, R + nanj, nan + Rj, nan + nanj] where R is a non-nan real value. Complex values with the same nan placements are sorted according to the non-nan part if it exists. Non-nan values are sorted as before. .. versionadded:: 1.12.0 quicksort has been changed to `introsort <https://en.wikipedia.org/wiki/Introsort>`_. When sorting does not make enough progress it switches to `heapsort <https://en.wikipedia.org/wiki/Heapsort>`_. This implementation makes quicksort O(n*log(n)) in the worst case. 'stable' automatically chooses the best stable sorting algorithm for the data type being sorted. It, along with 'mergesort' is currently mapped to `timsort <https://en.wikipedia.org/wiki/Timsort>`_ or `radix sort <https://en.wikipedia.org/wiki/Radix_sort>`_ depending on the data type. API forward compatibility currently limits the ability to select the implementation and it is hardwired for the different data types. .. versionadded:: 1.17.0 Timsort is added for better performance on already or nearly sorted data. On random data timsort is almost identical to mergesort. It is now used for stable sort while quicksort is still the default sort if none is chosen. For timsort details, refer to `CPython listsort.txt <https://github.com/python/cpython/blob/3.7/Objects/listsort.txt>`_. 'mergesort' and 'stable' are mapped to radix sort for integer data types. Radix sort is an O(n) sort instead of O(n log n). .. versionchanged:: 1.18.0 NaT now sorts to the end of arrays for consistency with NaN. Examples -------- >>> a = np.array([[1,4],[3,1]]) >>> np.sort(a) # sort along the last axis array([[1, 4], [1, 3]]) >>> np.sort(a, axis=None) # sort the flattened array array([1, 1, 3, 4]) >>> np.sort(a, axis=0) # sort along the first axis array([[1, 1], [3, 4]]) Use the `order` keyword to specify a field to use when sorting a structured array: >>> dtype = [('name', 'S10'), ('height', float), ('age', int)] >>> values = [('Arthur', 1.8, 41), ('Lancelot', 1.9, 38), ... ('Galahad', 1.7, 38)] >>> a = np.array(values, dtype=dtype) # create a structured array >>> np.sort(a, order='height') # doctest: +SKIP array([('Galahad', 1.7, 38), ('Arthur', 1.8, 41), ('Lancelot', 1.8999999999999999, 38)], dtype=[('name', '|S10'), ('height', '<f8'), ('age', '<i4')]) Sort by age, then height if ages are equal: >>> np.sort(a, order=['age', 'height']) # doctest: +SKIP array([('Galahad', 1.7, 38), ('Lancelot', 1.8999999999999999, 38), ('Arthur', 1.8, 41)], dtype=[('name', '|S10'), ('height', '<f8'), ('age', '<i4')]) File: /usr/local/lib/python3.7/dist-packages/numpy/core/fromnumeric.py Type: function
import numpy as np
np.random.seed(98554576)
np.random.random()
0.8089943552589222