gitee.com/quant1x/num@v0.3.2/ndarray.go (about)

     1  package num
     2  
     3  type ndarray[E BaseType] []E
     4  
     5  func (this *ndarray[E]) Shift(n any) ndarray[E] {
     6  	return Shift(*this, n)
     7  }
     8  
     9  // 切片边界检查
    10  func (this *ndarray[E]) checkBoundary(index int) bool {
    11  	length := len(*this)
    12  	return index >= 0 && index < length
    13  }
    14  
    15  func (this *ndarray[E]) Rolling(n any, apply func(index int, v E) E) []E {
    16  	return this.v2Rolling(n, apply)
    17  }
    18  
    19  func (this *ndarray[E]) v1Rolling(n any, apply func(index int, v E) E) []E {
    20  	length := len(*this)
    21  	d := make([]E, length)
    22  	window := Any2Window[DType](n)
    23  	defaultValue := TypeDefault[E]()
    24  	for i, v := range *this {
    25  		val := v
    26  		period := window.At(i)
    27  		if DTypeIsNaN(period) {
    28  			val = defaultValue
    29  		} else {
    30  			newIndex := i - int(period)
    31  			if newIndex < 0 || newIndex >= length {
    32  				val = defaultValue
    33  			} else {
    34  				val = apply(i, (*this)[newIndex])
    35  			}
    36  		}
    37  		d[i] = val
    38  	}
    39  
    40  	return d
    41  }
    42  
    43  func (this *ndarray[E]) v2Rolling(n any, apply func(index int, v E) E) []E {
    44  	length := len(*this)
    45  	d := make([]E, length)
    46  	window := Any2Window[DType](n)
    47  	defaultValue := TypeDefault[E]()
    48  	for i := 0; i < length; i++ {
    49  		val := (*this)[i]
    50  		period := window.At(i)
    51  		if DTypeIsNaN(period) {
    52  			val = defaultValue
    53  		} else {
    54  			newIndex := i - int(period)
    55  			if newIndex < 0 || newIndex >= length {
    56  				val = defaultValue
    57  			} else {
    58  				val = apply(i, (*this)[newIndex])
    59  			}
    60  		}
    61  		d[i] = val
    62  	}
    63  
    64  	return d
    65  }