1

入力のnumpy配列を操作できる、任意の数の間隔と関数を使用して区分関数を構築する必要があります。

以下のコードのスニペットに例示されているように、for ループとインジケーター配列を使用してそれを行うことができますが、それを行うためのより Pythonic な方法はありますか?

numpy.piecewise を使用しようとしましたが、私が知る限り、ソース コードでセグメントと関数の数を静的に定義する必要があります。

import numpy as np
import matplotlib.pyplot as plt 

# inputs:
#    -xs: points in which to compute the piecewise function
#    -segments: the extremes of the piecewise intervals (as a list)
#    -funcs: the functions (as a list; len(funcs)==len(segments)-1 )
def calc_piecewise(xs, segments, funcs):
    # prepare indicators and results arrays
    indaseg = np.zeros(len(xs), np.bool)
    ys = np.zeros_like(xs)

    # loop through intervals and compute the ys
    for ii in range(len(funcs)):
        indaseg = np.logical_and(xs>=segments[ii], xs<=segments[ii+1])
        ys[indaseg] = funcs[ii](xs[indaseg])

    return ys

def test_calc_piecewise():
    segments = [0.0, 1.0, 2.5, 4.0, 5.0]
    def f0(xs):
        return xs
    def f1(xs):
        return xs*xs
    def f2(xs):
        return 12.5-xs*xs
    def f3(xs):
        return 4.0*xs-19.5
    funcs = [f0, f1, f2, f3]

    xs = np.linspace(0.0, 5.0, 500)
    ys = calc_piecewise(xs, segments, funcs)

    plt.figure()
    title = "calc_piecewise"
    plt.title(title)
    plt.plot(xs, ys, 'r-')
    plt.show()

    return 


test_calc_piecewise()
4

1 に答える 1