예제 #1
0
    def __getitem__(self, key):
        # handle matrix builder syntax
        if isinstance(key, str):
            frame = sys._getframe().f_back
            mymat = matrixlib.bmat(key, frame.f_globals, frame.f_locals)
            return mymat

        if not isinstance(key, tuple):
            key = (key, )

        # copy attributes, since they can be overridden in the first argument
        trans1d = self.trans1d
        ndmin = self.ndmin
        matrix = self.matrix
        axis = self.axis

        objs = []
        scalars = []
        arraytypes = []
        scalartypes = []

        for k, item in enumerate(key):
            scalar = False
            if isinstance(item, slice):
                step = item.step
                start = item.start
                stop = item.stop
                if start is None:
                    start = 0
                if step is None:
                    step = 1
                if isinstance(step, complex):
                    size = int(abs(step))
                    newobj = linspace(start, stop, num=size)
                else:
                    newobj = _nx.arange(start, stop, step)
                if ndmin > 1:
                    newobj = array(newobj, copy=False, ndmin=ndmin)
                    if trans1d != -1:
                        newobj = newobj.swapaxes(-1, trans1d)
            elif isinstance(item, str):
                if k != 0:
                    raise ValueError("special directives must be the "
                                     "first entry.")
                if item in ('r', 'c'):
                    matrix = True
                    col = (item == 'c')
                    continue
                if ',' in item:
                    vec = item.split(',')
                    try:
                        axis, ndmin = [int(x) for x in vec[:2]]
                        if len(vec) == 3:
                            trans1d = int(vec[2])
                        continue
                    except Exception as e:
                        raise ValueError(
                            "unknown special directive {!r}".format(
                                item)) from e
                try:
                    axis = int(item)
                    continue
                except (ValueError, TypeError):
                    raise ValueError("unknown special directive")
            elif type(item) in ScalarType:
                newobj = array(item, ndmin=ndmin)
                scalars.append(len(objs))
                scalar = True
                scalartypes.append(newobj.dtype)
            else:
                item_ndim = ndim(item)
                newobj = array(item, copy=False, subok=True, ndmin=ndmin)
                if trans1d != -1 and item_ndim < ndmin:
                    k2 = ndmin - item_ndim
                    k1 = trans1d
                    if k1 < 0:
                        k1 += k2 + 1
                    defaxes = list(range(ndmin))
                    axes = defaxes[:k1] + defaxes[k2:] + defaxes[k1:k2]
                    newobj = newobj.transpose(axes)
            objs.append(newobj)
            if not scalar and isinstance(newobj, _nx.ndarray):
                arraytypes.append(newobj.dtype)

        # Ensure that scalars won't up-cast unless warranted
        final_dtype = find_common_type(arraytypes, scalartypes)
        if final_dtype is not None:
            for k in scalars:
                objs[k] = objs[k].astype(final_dtype)

        res = self.concatenate(tuple(objs), axis=axis)

        if matrix:
            oldndim = res.ndim
            res = self.makemat(res)
            if oldndim == 1 and col:
                res = res.T
        return res
예제 #2
0
from matplotlib import pyplot as plt
from numpy.core import linspace


for tau in [0.1, 0.2, 0.25]:
    y_arr = [2]
    z_arr = [1]

    t_end = 100
    N_tau = int(t_end / tau)
    for t in linspace(0, N_tau * tau, N_tau + 1):
        f_i_j = -y_arr[-1] + 0.999 * z_arr[-1]
        y_arr.append(y_arr[-1] + tau * (-(y_arr[-1] + tau/2*f_i_j) + 0.999 * (z_arr[-1] + tau/2)))
        z_arr.append(z_arr[-1] + tau * (-0.001 * (z_arr[-1] + tau/2*f_i_j)))

    plt.plot(y_arr, z_arr, label=f'tau: {tau}')

plt.legend()
plt.show()
예제 #3
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import math
import numpy.core as np

pisobre2 = math.pi / 2.0


#Defino funcion
def f1(x):
    return 13.0 / (12.0 * math.pi) - (x**2) / math.pi**3


#Defino limites
x1 = np.linspace(-3.0, -pisobre2)
x2 = np.linspace(-pisobre2, pisobre2)
x3 = np.linspace(pisobre2, 3.0)

#Armo el gráfico
plt.plot(x1, [0.0 for x in x1], 'm', label='y = 2, x en [-oo, -pi/2]')
plt.plot(x2, [f1(i) for i in x2],
         'm',
         label='y = 13/(12*pi) - (x**2)/pi**3, x en [-pi/2, pi/2]')
plt.plot(x3, [0 for x in x3], 'm', label='y = 0, x en (pi/2, oo]')
plt.plot(-pisobre2,
         0,
         'mo',
         markersize=5,
         fillstyle='none',
         markerfacecolor='w')
예제 #4
0
파일: index_tricks.py 프로젝트: esc/numpy
    def __getitem__(self, key):
        # handle matrix builder syntax
        if isinstance(key, str):
            frame = sys._getframe().f_back
            mymat = matrixlib.bmat(key, frame.f_globals, frame.f_locals)
            return mymat

        if not isinstance(key, tuple):
            key = (key,)

        # copy attributes, since they can be overridden in the first argument
        trans1d = self.trans1d
        ndmin = self.ndmin
        matrix = self.matrix
        axis = self.axis

        objs = []
        scalars = []
        arraytypes = []
        scalartypes = []

        for k, item in enumerate(key):
            scalar = False
            if isinstance(item, slice):
                step = item.step
                start = item.start
                stop = item.stop
                if start is None:
                    start = 0
                if step is None:
                    step = 1
                if isinstance(step, complex):
                    size = int(abs(step))
                    newobj = linspace(start, stop, num=size)
                else:
                    newobj = _nx.arange(start, stop, step)
                if ndmin > 1:
                    newobj = array(newobj, copy=False, ndmin=ndmin)
                    if trans1d != -1:
                        newobj = newobj.swapaxes(-1, trans1d)
            elif isinstance(item, str):
                if k != 0:
                    raise ValueError("special directives must be the "
                            "first entry.")
                if item in ('r', 'c'):
                    matrix = True
                    col = (item == 'c')
                    continue
                if ',' in item:
                    vec = item.split(',')
                    try:
                        axis, ndmin = [int(x) for x in vec[:2]]
                        if len(vec) == 3:
                            trans1d = int(vec[2])
                        continue
                    except Exception:
                        raise ValueError("unknown special directive")
                try:
                    axis = int(item)
                    continue
                except (ValueError, TypeError):
                    raise ValueError("unknown special directive")
            elif type(item) in ScalarType:
                newobj = array(item, ndmin=ndmin)
                scalars.append(len(objs))
                scalar = True
                scalartypes.append(newobj.dtype)
            else:
                item_ndim = ndim(item)
                newobj = array(item, copy=False, subok=True, ndmin=ndmin)
                if trans1d != -1 and item_ndim < ndmin:
                    k2 = ndmin - item_ndim
                    k1 = trans1d
                    if k1 < 0:
                        k1 += k2 + 1
                    defaxes = list(range(ndmin))
                    axes = defaxes[:k1] + defaxes[k2:] + defaxes[k1:k2]
                    newobj = newobj.transpose(axes)
            objs.append(newobj)
            if not scalar and isinstance(newobj, _nx.ndarray):
                arraytypes.append(newobj.dtype)

        # Ensure that scalars won't up-cast unless warranted
        final_dtype = find_common_type(arraytypes, scalartypes)
        if final_dtype is not None:
            for k in scalars:
                objs[k] = objs[k].astype(final_dtype)

        res = self.concatenate(tuple(objs), axis=axis)

        if matrix:
            oldndim = res.ndim
            res = self.makemat(res)
            if oldndim == 1 and col:
                res = res.T
        return res
예제 #5
0
print(arr)
print(arr.dtype)

'iplicit conversion'
arr1=array([1,5,7,8.0])
print(arr1.dtype)

'assigning type to array'
arr2=array([1,5,7,8.0],int)
print(arr2.dtype)



'linspace(it has 3 parameter 1.start 2.end_includeed 3.numberofparts and 3rd one is optional if it is not defined then it will divide in 50 equal parts) for array'

arr3 = linspace(0,15,16)
print(arr3)


'arange (it has 3 parameter 1.start 2.end_excluded 3.range and 3rd one is optional if it is not defined then range will be 1)'
arr4 = arange(0,15,3)
print(arr4)

'logspace'
arr5 = logspace(1,40,5)
print(arr5)
print('%.2f.'%arr5[4])

'Zeros'
arr6 = zeros(5)
arr7 = zeros(5,int)