Python sys.float_info.epsilon() Examples

The following are 11 code examples of sys.float_info.epsilon(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module sys.float_info , or try the search function .
Example #1
Source File: xferfcn.py    From python-control with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def minreal(self, tol=None):
        """Remove cancelling pole/zero pairs from a transfer function"""
        # based on octave minreal

        # default accuracy
        from sys import float_info
        sqrt_eps = sqrt(float_info.epsilon)

        # pre-allocate arrays
        num = [[[] for j in range(self.inputs)] for i in range(self.outputs)]
        den = [[[] for j in range(self.inputs)] for i in range(self.outputs)]

        for i in range(self.outputs):
            for j in range(self.inputs):

                # split up in zeros, poles and gain
                newzeros = []
                zeros = roots(self.num[i][j])
                poles = roots(self.den[i][j])
                gain = self.num[i][j][0] / self.den[i][j][0]

                # check all zeros
                for z in zeros:
                    t = tol or \
                        1000 * max(float_info.epsilon, abs(z) * sqrt_eps)
                    idx = where(abs(z - poles) < t)[0]
                    if len(idx):
                        # cancel this zero against one of the poles
                        poles = delete(poles, idx[0])
                    else:
                        # keep this zero
                        newzeros.append(z)

                # poly([]) returns a scalar, but we always want a 1d array
                num[i][j] = np.atleast_1d(gain * real(poly(newzeros)))
                den[i][j] = np.atleast_1d(real(poly(poles)))

        # end result
        return TransferFunction(num, den, self.dt) 
Example #2
Source File: execution.py    From pylivetrader with Apache License 2.0 5 votes vote down vote up
def asymmetric_round_price_to_penny(price, prefer_round_down,
                                    diff=(0.0095 - .005)):
    """
    Asymmetric rounding function for adjusting prices to two places in a way
    that "improves" the price.  For limit prices, this means preferring to
    round down on buys and preferring to round up on sells.  For stop prices,
    it means the reverse.

    If prefer_round_down == True:
        When .05 below to .95 above a penny, use that penny.
    If prefer_round_down == False:
        When .95 below to .05 above a penny, use that penny.

    In math-speak:
    If prefer_round_down: [<X-1>.0095, X.0195) -> round to X.01.
    If not prefer_round_down: (<X-1>.0005, X.0105] -> round to X.01.
    """
    # Subtracting an epsilon from diff to enforce the open-ness of the upper
    # bound on buys and the lower bound on sells.  Using the actual system
    # epsilon doesn't quite get there, so use a slightly less epsilon-ey value.
    epsilon = float_info.epsilon * 10
    diff = diff - epsilon

    # relies on rounding half away from zero, unlike numpy's bankers' rounding
    rounded = round(price - (diff if prefer_round_down else -diff), 2)
    if zp_math.tolerant_equals(rounded, 0.0):
        return 0.0
    return rounded 
Example #3
Source File: _editex.py    From abydos with GNU General Public License v3.0 5 votes vote down vote up
def _taper(self, pos: int, length: int) -> float:
        return (
            round(
                1.0 + ((length - pos) / length) * (1 + float_info.epsilon), 15
            )
            if self._taper_enabled
            else 1.0
        ) 
Example #4
Source File: _levenshtein.py    From abydos with GNU General Public License v3.0 5 votes vote down vote up
def _taper(self, pos: int, length: int) -> float:
        return (
            round(1 + ((length - pos) / length) * (1 + float_info.epsilon), 15)
            if self._taper_enabled
            else 1
        ) 
Example #5
Source File: uwapm.py    From arlpy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def plot_arrivals(arrivals, dB=False, color='blue', **kwargs):
    """Plots the arrival times and amplitudes.

    :param arrivals: arrivals times (s) and coefficients
    :param dB: True to plot in dB, False for linear scale
    :param color: line color (see `Bokeh colors <https://bokeh.pydata.org/en/latest/docs/reference/colors.html>`_)

    Other keyword arguments applicable for `arlpy.plot.plot()` are also supported.

    >>> import arlpy.uwapm as pm
    >>> env = pm.create_env2d()
    >>> arrivals = pm.compute_arrivals(env)
    >>> pm.plot_arrivals(arrivals)
    """
    t0 = min(arrivals.time_of_arrival)
    t1 = max(arrivals.time_of_arrival)
    oh = _plt.hold()
    if dB:
        min_y = 20*_np.log10(_np.max(_np.abs(arrivals.arrival_amplitude)))-60
        ylabel = 'Amplitude (dB)'
    else:
        ylabel = 'Amplitude'
        _plt.plot([t0, t1], [0, 0], xlabel='Arrival time (s)', ylabel=ylabel, color=color, **kwargs)
        min_y = 0
    for _, row in arrivals.iterrows():
        t = row.time_of_arrival.real
        y = _np.abs(row.arrival_amplitude)
        if dB:
            y = max(20*_np.log10(_fi.epsilon+y), min_y)
        _plt.plot([t, t], [min_y, y], xlabel='Arrival time (s)', ylabel=ylabel, ylim=[min_y, min_y+70], color=color, **kwargs)
    _plt.hold(oh) 
Example #6
Source File: uwapm.py    From arlpy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def plot_transmission_loss(tloss, env=None, **kwargs):
    """Plots transmission loss.

    :param tloss: complex transmission loss
    :param env: environment definition

    If environment definition is provided, it is overlayed over this plot using default
    parameters for `arlpy.uwapm.plot_env()`.

    Other keyword arguments applicable for `arlpy.plot.image()` are also supported.

    >>> import arlpy.uwapm as pm
    >>> import numpy as np
    >>> env = pm.create_env2d(
            rx_depth=np.arange(0, 25),
            rx_range=np.arange(0, 1000),
            min_angle=-45,
            max_angle=45
        )
    >>> tloss = pm.compute_transmission_loss(env)
    >>> pm.plot_transmission_loss(tloss, width=1000)
    """
    xr = (min(tloss.columns), max(tloss.columns))
    yr = (-max(tloss.index), -min(tloss.index))
    xlabel = 'Range (m)'
    if xr[1]-xr[0] > 10000:
        xr = (min(tloss.columns)/1000, max(tloss.columns)/1000)
        xlabel = 'Range (km)'
    oh = _plt.hold()
    _plt.image(20*_np.log10(_fi.epsilon+_np.abs(_np.flipud(_np.array(tloss)))), x=xr, y=yr, xlabel=xlabel, ylabel='Depth (m)', xlim=xr, ylim=yr, **kwargs)
    if env is not None:
        plot_env(env, rx_plot=False)
    _plt.hold(oh) 
Example #7
Source File: execution.py    From zipline-chinese with Apache License 2.0 5 votes vote down vote up
def asymmetric_round_price_to_penny(price, prefer_round_down,
                                    diff=(0.0095 - .005)):
    """
    Asymmetric rounding function for adjusting prices to two places in a way
    that "improves" the price.  For limit prices, this means preferring to
    round down on buys and preferring to round up on sells.  For stop prices,
    it means the reverse.

    If prefer_round_down == True:
        When .05 below to .95 above a penny, use that penny.
    If prefer_round_down == False:
        When .95 below to .05 above a penny, use that penny.

    In math-speak:
    If prefer_round_down: [<X-1>.0095, X.0195) -> round to X.01.
    If not prefer_round_down: (<X-1>.0005, X.0105] -> round to X.01.
    """
    # Subtracting an epsilon from diff to enforce the open-ness of the upper
    # bound on buys and the lower bound on sells.  Using the actual system
    # epsilon doesn't quite get there, so use a slightly less epsilon-ey value.
    epsilon = float_info.epsilon * 10
    diff = diff - epsilon

    # relies on rounding half away from zero, unlike numpy's bankers' rounding
    rounded = round(price - (diff if prefer_round_down else -diff), 2)
    if zp_math.tolerant_equals(rounded, 0.0):
        return 0.0
    return rounded 
Example #8
Source File: utils.py    From pandas-ta with MIT License 5 votes vote down vote up
def non_zero_range(high: pd.Series, low: pd.Series) -> pd.Series:
    """Returns the difference of two series and adds epsilon if
    to any zero values.  This occurs commonly in crypto data when
    high = low.
    """
    diff = high - low
    if diff.eq(0).any().any():
        diff += sflt.epsilon
    return diff 
Example #9
Source File: utils.py    From pandas-ta with MIT License 5 votes vote down vote up
def zero(x: [int, float]) -> [int, float]:
    """If the value is close to zero, then return zero.
    Otherwise return the value."""
    return 0 if -sflt.epsilon < x and x < sflt.epsilon else x 
Example #10
Source File: _fellegi_sunter.py    From abydos with GNU General Public License v3.0 4 votes vote down vote up
def sim_score(self, src: str, tar: str) -> float:
        """Return the Fellegi-Sunter similarity of two strings.

        Parameters
        ----------
        src : str
            Source string (or QGrams/Counter objects) for comparison
        tar : str
            Target string (or QGrams/Counter objects) for comparison

        Returns
        -------
        float
            Fellegi-Sunter similarity

        Examples
        --------
        >>> cmp = FellegiSunter()
        >>> cmp.sim_score('cat', 'hat')
        0.8803433378011485
        >>> cmp.sim_score('Niall', 'Neil')
        0.6958768466635681
        >>> cmp.sim_score('aluminum', 'Catalan')
        0.45410905865149187
        >>> cmp.sim_score('ATCG', 'TAGC')
        0.0


        .. versionadded:: 0.4.0

        """
        self._tokenize(src, tar)
        src_tokens, tar_tokens = self._get_tokens()

        src_total = sum(src_tokens.values())
        tar_total = sum(tar_tokens.values())
        src_unique = len(src_tokens)
        tar_unique = len(tar_tokens)

        similarity = 0.0
        for _tok, count in self._intersection().items():
            if self._simplified:
                similarity += -log(count / tar_total)
            else:
                prob = count / tar_total
                similarity -= log(
                    1
                    + float_info.epsilon
                    - exp(
                        src_unique
                        * tar_unique
                        * log(1 + float_info.epsilon - prob * prob)
                    )
                )

        for _tok, count in self._src_only().items():
            if self._simplified:
                similarity -= -log(count / src_total) * self._mismatch_factor

        return similarity 
Example #11
Source File: _intervalarray.py    From nelpy with MIT License 4 votes vote down vote up
def partition(self, *, ds=None, n_intervals=None):
        """Returns an IntervalArray that has been partitioned.

        # Irrespective of whether 'ds' or 'n_intervals' are used, the exact
        # underlying support is propagated, and the first and last points
        # of the supports are always included, even if this would cause
        # n_points or ds to be violated.

        Parameters
        ----------
        ds : float, optional
            Maximum length, for each interval.
        n_points : int, optional
            Number of intervals. If ds is None and n_intervals is None, then
            default is to use n_intervals = 100

        Returns
        -------
        out : IntervalArray
            IntervalArray that has been partitioned.
        """

        if self.isempty:
            raise ValueError ("cannot parition an empty object in a meaningful way!")

        if ds is not None and n_intervals is not None:
            raise ValueError("ds and n_intervals cannot be used together")

        if n_intervals is not None:
            assert float(n_intervals).is_integer(), "n_intervals must be a positive integer!"
            assert n_intervals > 1, "n_intervals must be a positive integer > 1"
            # determine ds from number of desired points:
            ds = self.length / n_intervals

        if ds is None:
            # neither n_intervals nor ds was specified, so assume defaults:
            n_intervals = 100
            ds = self.length / n_intervals

        # build list of points at which to esplit the IntervalArray
        new_starts = []
        new_stops = []
        for start, stop in self.data:
            newxvals = utils.frange(start, stop, step=ds).tolist()
            # newxvals = np.arange(start, stop, step=ds).tolist()
            if newxvals[-1] + float_info.epsilon < stop:
                newxvals.append(stop)
            newxvals = np.asanyarray(newxvals)
            new_starts.extend(newxvals[:-1])
            new_stops.extend(newxvals[1:])

        # now make a new interval array:
        out = copy.copy(self)
        out._data = np.hstack(
                [np.array(new_starts)[..., np.newaxis],
                 np.array(new_stops)[..., np.newaxis]])
        return out