简体   繁体   中英

Precision loss in numpy.linspace when including the endpoint

I'm trying to iterate over the product of two windowed linspaces in order to explore a space. When I include the endpoint, I seem to lose linspace's precision. Am I garbling the types somehow? Is there something in numpy to do this that is preferred?

Here's some demo code. I updated numpy in hopes of a fix, but that didn't help (1.16.4, python 3.7.3).

import numpy as np
import itertools

# Windowing func from old itertools docs
def window(seq, n=2):
    "Returns a sliding window (of width n) over data from the iterable"
    "   s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ...                   "
    it = iter(seq)
    result = tuple(itertools.islice(it, n))
    if len(result) == n:
        yield result
    for elem in it:
        result = result[1:] + (elem,)
        yield result

for (a,b) in itertools.product(window(np.linspace(12, 13, 10, endpoint=False)), window(np.linspace(20,21,10, endpoint=False))):
    print(a, b)
for (a,b) in itertools.product(window(np.linspace(12, 13, 10, endpoint=True)), window(np.linspace(20,21,10, endpoint=True))):
    print(a, b)

Without endpoint:

(12.0, 12.1) (20.0, 20.1)
(12.0, 12.1) (20.1, 20.2)
(12.0, 12.1) (20.2, 20.3)
...

With endpoint:

(12.0, 12.11111111111111) (20.0, 20.11111111111111)
(12.0, 12.11111111111111) (20.11111111111111, 20.22222222222222)
(12.0, 12.11111111111111) (20.22222222222222, 20.333333333333332)
...

您想要的linspace输出有11 个元素,但您要求的是 10。要求 11。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM