num

package module
v0.2.9 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 16, 2024 License: MIT Imports: 21 Imported by: 22

README

num

Sourcegraph Build Status codecov tag license

1. 介绍

num 是go语言实现的类似numpy的工具包

2. 模块划分

3. 示例

4. 参考及依赖

  • 级别说明: 0-引用, 1-fork引入有调整, 2-参考和复制部分代码
级别 功能 名称 版本 地址 依赖
0 SIMD avo 0.6.0 https://github.com/mmcloughlin/avo
1 SIMD vek 0.4.2 https://github.com/viterin/vek avo
1 plan9 asm2plan9s - https://github.com/minio/asm2plan9s.git 停止维护
1 plan9 c2goasm - https://github.com/minio/c2goasm.git 停止维护
2 小众功能 cyan 0.4.2 https://github.com/dablelv/cyan

Documentation

Index

Constants

View Source
const (
	Unchanged       = 0  // 趋势不变
	BreakThrough    = 1  // break through 突破
	FallDrastically = -1 // fall drastically 跌破
)

趋势变化

View Source
const (
	TendencyUnchanged       = 0  // 趋势不变
	TendencyBreakThrough    = 1  // break through 突破
	TendencyFallDrastically = -1 // fall drastically 跌破
)

趋势变化

View Source
const (
	Nil2Bool              = false      // 空指针转bool
	BoolNaN               = false      // bool 无效值
	True2Bool             = true       // true转bool
	False2Bool            = false      // false 转bool
	True2Float32  float32 = float32(1) // true转float32
	False2Float32 float32 = float32(0) // false转float32

	StringBad2Bool   = false // 字符串解析bool异常
	StringTrue2Bool  = true  // 字符串true转bool
	StringFalse2Bool = false // 字符串false转bool
)
View Source
const (
	MaxFloat32                  = float32(math.MaxFloat32)             // float32最大值
	MinFloat32                  = float32(math.SmallestNonzeroFloat32) // float32最小值
	StringTrue2Float32  float32 = float32(1)                           // 字符串true转float32
	StringFalse2Float32 float32 = float32(0)                           // 字符串false转float32
)
View Source
const (
	MaxFloat64          float64 = float64(math.MaxFloat64)             // float64最大值
	MinFloat64          float64 = float64(math.SmallestNonzeroFloat64) // float64最小值
	True2Float64        float64 = float64(1)                           // true转float64
	False2Float64       float64 = float64(0)                           // false转float64
	StringNil2Float     float64 = float64(0)                           // deprecated: 字符串空指针转float64
	StringBad2Float     float64 = float64(0)                           // deprecated: 字符串解析float64异常
	StringTrue2Float64  float64 = float64(1)                           // 字符串true转float64
	StringFalse2Float64 float64 = float64(0)                           // 字符串false转float64
)
View Source
const (
	MaxInt32          = int32(math.MaxInt32)
	MinInt32          = int32(math.MinInt32)
	Nil2Int32         = int32(0) // 空指针转int32
	Int32NaN          = int32(0) // int32 无效值
	True2Int32        = int32(1) // true转int32
	False2Int32       = int32(0) // false 转int32
	StringBad2Int32   = int32(0) // 字符串解析int32异常
	StringTrue2Int32  = int32(1) // 字符串true转int32
	StringFalse2Int32 = int32(0) // 字符串false转int32
)
View Source
const (
	MaxInt64          = int64(math.MaxInt64)
	MinInt64          = int64(math.MinInt64)
	Nil2Int64         = int64(0) // 空指针转int64
	Int64NaN          = int64(0) // int64 无效值
	True2Int64        = int64(1) // true转int64
	False2Int64       = int64(0) // false 转int64
	StringBad2Int64   = int64(0) // 字符串解析int64异常
	StringTrue2Int64  = int64(1) // 字符串true转int64
	StringFalse2Int64 = int64(0) // 字符串false转int64
)
View Source
const (
	StringNaN    = "NaN"   // 字符串NaN
	Nil2String   = "NaN"   // nil指针转string
	True2String  = "true"  // true转string
	False2String = "false" // false转string
)

Variables

View Source
var (
	// ErrUnsupportedType 不支持的类型
	ErrUnsupportedType = errors.New("unsupported type")
	ErrRange           = errors.New("range error")
	ErrInvalidWindow   = errors.New("error window")
)
View Source
var (
	IgnoreParseExceptions = true // 忽略解析异常
)
View Source
var (
	// PossibleNaOfString 有可能出现的NaN字符串的全部选项
	PossibleNaOfString = []string{"NA", "NaN", "nan", "<nil>"}
)

Functions

func Abs

func Abs[T BaseType](x []T) []T

Abs 泛型绝对值

func AbsFloat32 added in v0.1.0

func AbsFloat32(n float32) float32

func AbsFloat64 added in v0.1.0

func AbsFloat64(n float64) float64

func AbsInt added in v0.1.3

func AbsInt(n int) int

AbsInt gets absolute value of int.

func AbsInt16 added in v0.1.0

func AbsInt16(n int16) int16

AbsInt16 gets absolute value of int16.

func AbsInt32 added in v0.1.0

func AbsInt32(n int32) int32

AbsInt32 gets absolute value of int32.

func AbsInt64 added in v0.1.0

func AbsInt64(n int64) int64

AbsInt64 gets absolute value of int64.

func AbsInt8 added in v0.1.0

func AbsInt8(n int8) int8

AbsInt8 gets absolute value of int8.

Example 1: AbsInt8(-5) -5 code value as below original code 1000,0101 inverse code 1111,1010 complement code 1111,1011 Negative numbers are represented by complement code in memory. shifted = n >> 7 = (1111,1011) >> 7 = 1111,1111 = -1(10-base) (负数右移,左补1)

1111,1011

n xor shifted = ----------- = 0000,0100 = 4(10-base)

1111,1111

(n ^ shifted) - shifted = 4 - (-1) = 5

Example 2: AbsInt8(5) 5 code value as below original code 0000,0101 Positive numbers are represented by original code in memory, and the XOR operation between positive numbers and 0 is equal to itself. shifted = n >> 7 = 0

0000,0101

n xor shifted = ----------- = 0000,0101 = 5(10-base)

0000,0000

(n ^ shifted) - shifted = 5 - 0 = 5

func Add

func Add[T Number](x []T, y any) []T

Add arithmetics 加法

func Align

func Align[E BaseType](x []E, a E, n int) []E

Align data alignment

a 通常是默认值

func All

func All[T Number | ~bool](x []T) bool

All 全部为真

func And

func And[S ~[]E, E any](v S, x any) []bool

And 比较 v && x

func Any

func Any[T Number | ~bool](x []T) bool

Any 任意一个为真

func AnyToBool

func AnyToBool(v any) bool

AnyToBool any转换bool

func AnyToFloat32

func AnyToFloat32(v any) float32

func AnyToFloat64

func AnyToFloat64(v any) float64

func AnyToGeneric

func AnyToGeneric[T BaseType](v any) T

AnyToGeneric any转其它类型, 推导T的类型 支持3个方向: any到number, any到bool, any到string

func AnyToInt32

func AnyToInt32(v any) int32

AnyToInt32 any转换int32

func AnyToInt64

func AnyToInt64(v any) int64

AnyToInt64 any转换int64

func AnyToSlice

func AnyToSlice[T BaseType](A any, N int) []T

AnyToSlice any转切片

如果a是基础类型, 就是repeat
如果a是切片, 就做对齐处理, 截断或者填充

func AnyToString

func AnyToString(v any) string

AnyToString any转string

func Arange

func Arange[T Number](start T, end T, argv ...T) []T

Arange Return evenly spaced values within a given interval.

返回给定间隔内的等间距值

func ArgMax

func ArgMax[T Number](x []T) int

ArgMax Returns the indices of the maximum values along an axis.

返回轴上最大值的索引

func ArgMax2

func ArgMax2[T BaseType](x []T) int

func ArgMin

func ArgMin[T Number](x []T) int

ArgMin Returns the indices of the minimum values along an axis.

返回轴上最小值的索引

func ArgMin2

func ArgMin2[T BaseType](x []T) int

func BinaryOperations

func BinaryOperations[T Number](x []T, y any, f32 func(x, y []float32) []float32, f64 func(x, y []float64) []float64, cany func(x, y []T) []T) []T

BinaryOperations 二元运算 binary operations

Binary operation
calculate

func BinaryOperations2

func BinaryOperations2[T BaseType, E BaseType](x, y []T, f32 func(x, y []float32) []E, f64 func(x, y []float64) []E, cany func(x, y []T) []E) []E

func BoolToFloat32

func BoolToFloat32(b bool) float32

BoolToFloat32 bool转float32

func BoolToFloat64

func BoolToFloat64(b bool) float64

BoolToFloat64 bool转float64

func BoolToInt

func BoolToInt(b bool) int8

func BoolToInt32

func BoolToInt32(b bool) int32

func BoolToInt64

func BoolToInt64(b bool) int64

func BoolToString

func BoolToString(b bool) string

BoolToString bool 转 string

func ChangeRate

func ChangeRate[B Number, C Number](baseValue B, currentValue C) (changeRate float64)

ChangeRate 增长率

func CheckoutRawType

func CheckoutRawType(frame any) reflect.Kind

CheckoutRawType 从泛型检测出类型

func Concat1D

func Concat1D[T Number](a, b, c []T) [][]T

Concat1D

Translates slice objects to concatenation along the second axis.
沿第二个轴将切片对象转换为串联

func ConfidenceIntervalToZscore

func ConfidenceIntervalToZscore(confidenceInterval float64) (zScore float64)

ConfidenceIntervalToZscore 通过置信区间百分比查找Z分值

func Count

func Count[T Number | ~bool](x []T) int

Count 统计

func Covariance added in v0.2.9

func Covariance(x, y []float64) float64

Covariance 协方差

func CumSum

func CumSum[T Number](x []T) []T

CumSum 计算累和

func DType2Int

func DType2Int(d []DType) []int32

DType2Int DType切片转int32切片

func DTypeIsNaN

func DTypeIsNaN(d DType) bool

DTypeIsNaN 判断DType是否NaN

func Decimal

func Decimal(value float64, digits ...int) float64

Decimal 保留小数点四舍五入

func DefaultFormatter

func DefaultFormatter(v any) string

DefaultFormatter will return a string representation of the data in a particular row.

func DegreesToSlope added in v0.1.4

func DegreesToSlope(x float64) float64

DegreesToSlope 角度转斜率

func Diff

func Diff[E Number](S []E, n int) []E

Diff 元素的第一个离散差

n默认是1

func Div

func Div[T Number](x []T, y any) []T

Div arithmetics 除法

func Dot

func Dot[T Number](a, b [][]T) [][]T

Dot 二维点积

func Dot1D

func Dot1D[T Number](a, b []T) T

func Dot2D

func Dot2D[T Number](a, b [][]T) [][]T

Dot2D 二维矩阵点积

点积(dot)运算及简单应用 https://www.jianshu.com/p/482abac8798c

func Dot2D1

func Dot2D1[T Number](a [][]T, b []T) []T

Dot2D1 二维矩阵和一维矩阵计算点积

func Dot2D1_v2

func Dot2D1_v2[T Number](a [][]T, b []T) []T

func Dot2D_V1

func Dot2D_V1[T Number](a, b [][]T) [][]T

func Dot_v1

func Dot_v1[T Number](a, b [][]T) [][]T

func Equal

func Equal[T BaseType](x, y []T) []bool

Equal 比较相等

func ExtractValueFromPointer

func ExtractValueFromPointer(v any) (any, bool)

ExtractValueFromPointer 从指针/地址提取值 Extract value from pointer

func Fill

func Fill[T BaseType](v []T, d T, args ...any) (rows []T)

Fill 填充

Fill NA/NaN values using the specified method.
Parameters
----------
value : scalar, dict, Series, or DataFrame
   Value to use to fill holes (e.g. 0), alternately a
   dict/Series/DataFrame of values specifying which value to use for
   each index (for a Series) or column (for a DataFrame).  Values not
   in the dict/Series/DataFrame will not be filled. This value cannot
   be a list.
method : {{'backfill', 'bfill', 'pad', 'ffill', None}}, default None
   Method to use for filling holes in reindexed Series
   pad / ffill: propagate last valid observation forward to next valid
   backfill / bfill: use next valid observation to fill gap.
axis : {axes_single_arg}
   Axis along which to fill missing values. For `Series`
   this parameter is unused and defaults to 0.
inplace : bool, default False [√]
   If True, fill in-place. Note: this will modify any
   other views on this object (e.g., a no-copy slice for a column in a
   DataFrame).
limit : int, default None
   If method is specified, this is the maximum number of consecutive
   NaN values to forward/backward fill. In other words, if there is
   a gap with more than this number of consecutive NaNs, it will only
   be partially filled. If method is not specified, this is the
   maximum number of entries along the entire axis where NaNs will be
   filled. Must be greater than 0 if not None.
downcast : dict, default is None
   A dict of item->dtype of what to downcast if possible,
   or the string 'infer' which will try to downcast to an appropriate
   equal type (e.g. float64 to int64 if possible).

Returns
-------
[]T or None

func FillNa

func FillNa[T BaseType](x []T, v any, args ...any) []T

FillNa NaN填充默认值

func FindPercent

func FindPercent(zScore float64) (percent float64)

func FindZScore

func FindZScore(percent float64) (zScore float64)

func Float32IsNaN

func Float32IsNaN(f float32) bool

Float32IsNaN 判断float32是否NaN

func Float32NaN added in v0.0.6

func Float32NaN() float32

func Float64IsNaN

func Float64IsNaN(f float64) bool

Float64IsNaN 判断float64是否NaN

func Float64NaN added in v0.0.6

func Float64NaN() float64

Float64NaN returns an IEEE 754 “not-a-number” value.

func GenericParse

func GenericParse[T BaseType](text string) T

GenericParse 泛型解析

func GetAvx2Enabled

func GetAvx2Enabled() bool

GetAvx2Enabled 获取avx2加速状态

func Gt

func Gt[S ~[]E, E any](v S, x any) []bool

Gt 比较 v > x

func Gte

func Gte[S ~[]E, E any](v S, x any) []bool

Gte 比较 v >= x

func Inverse

func Inverse(a [][]float64) [][]float64

Inverse 计算矩阵的(乘法)逆

Compute the (multiplicative) inverse of a matrix.

Given a square matrix `a`, return the matrix `ainv` satisfying
``dot(a, ainv) = dot(ainv, a) = eye(a.shape[0])``.

func IsEmpty

func IsEmpty(s string) bool

IsEmpty Code to test if string is empty

func IsNaN

func IsNaN(f float64) bool

func Lt

func Lt[S ~[]E, E any](v S, x any) []bool

Lt 比较 v < x

func Lte

func Lte[S ~[]E, E any](v S, x any) []bool

Lte 比较 v <= x

func Max

func Max[T Number](x []T) T

Max 纵向计算x最大值

func Max2

func Max2[T BaseType](x []T) T

func Maximum

func Maximum[T Number](f1, f2 []T) []T

Maximum AVX2版本, 两个序列横向比较最大值

TODO:print(np.maximum(1.4, np.nan)) 输出nan

func Mean

func Mean[T Number](x []T) T

Mean 求均值

func Mean2

func Mean2[T BaseType](x []T) T

func Min

func Min[T Number](x []T) T

Min 纵向计算x最小值

func Min2

func Min2[T BaseType](x []T) T

func Minimum

func Minimum[T Number](f1, f2 []T) []T

Minimum AVX2版本, 两个序列横向比较最大值

func Mul

func Mul[T Number](x []T, y any) []T

Mul arithmetics 乘法

func NetChangeRate

func NetChangeRate[B Number, C Number](baseValue B, currentValue C) (changeRate float64)

NetChangeRate 净增长率, 去掉百分比

func Not

func Not[S ~[]E, E any](v S) []bool

Not 非

func NotEqual

func NotEqual[T BaseType](x, y []T) []bool

NotEqual 不相等

func Ones

func Ones[T Number](v []T) []T

Ones v -> shape

func Or

func Or[S ~[]E, E any](v S, x any) []bool

Or 比较 v || x

func PanicTrace

func PanicTrace(err interface{}) string

PanicTrace panic 堆栈信息

func ParseBool

func ParseBool(s string, v any) bool

ParseBool 字符串转bool

任意组合的nan字符串都会被解析成NaN

func ParseFloat32

func ParseFloat32(s string, v any) float32

ParseFloat32 字符串转float32

func ParseFloat64

func ParseFloat64(s string, v any) float64

ParseFloat64 字符串转float64 任意组合的nan字符串都会被解析成NaN

func ParseInt32

func ParseInt32(s string, v any) int32

ParseInt32 解析int字符串, 尝试解析10进制和16进制

func ParseInt64

func ParseInt64(s string, v any) int64

ParseInt64 解析int字符串, 尝试解析10进制和16进制

func PeeksAndValleys added in v0.1.4

func PeeksAndValleys[E Number](x []E) (peeks, valleys []int)

func Pow

func Pow[T Number](v []T, n int) []T

func PrintString

func PrintString(v any) string

func Range

func Range[E Number](n int) []E

Range 产生从0到n-1的数组

func Repeat

func Repeat[E BaseType](x E, n int) []E

Repeat 构造n长度的x的泛型切片

func RepeatInto

func RepeatInto[E BaseType](s []E, a E, n int) []E

RepeatInto 替换n长度的a的泛型切片

func Rolling

func Rolling[E BaseType](S []E, N any) [][]E

Rolling returns an array with elements that roll beyond the last position are re-introduced at the first. 滑动窗口, 数据不足是用空数组占位

func RollingV1 added in v0.1.3

func RollingV1[E BaseType](S []E, N any, apply func(N DType, values ...E) E) []E

RollingV1 泛型滑动窗口

滑动窗口参数N必须是数

func SetAvx2Enabled

func SetAvx2Enabled(enabled bool)

SetAvx2Enabled 设定AVX2加速开关, 非线程安全

func Shape

func Shape[T Number](x any) (r, c int)

Shape 返回一维或2维数组的行数和列数

func Shift

func Shift[E BaseType](S []E, N any) []E

Shift 使用可选的时间频率按所需的周期数移动索引

N 支持前后移动, N>0 向右, N<0 向左

func SliceFloatToInt32 added in v0.1.0

func SliceFloatToInt32[T Float](x []T) []int32

SliceFloatToInt32 浮点转int32

func SliceFloatToInt64 added in v0.1.0

func SliceFloatToInt64[T Float](x []T) []int64

SliceFloatToInt64 浮点转int64

func SliceToBool

func SliceToBool(v any) []bool

SliceToBool any输入只能是一维slice或者数组

func SliceToFloat32

func SliceToFloat32(v any) []float32

SliceToFloat32 any输入只能是一维slice或者数组

func SliceToFloat64

func SliceToFloat64(v any) []float64

SliceToFloat64 any输入只能是一维slice或者数组

func SliceToInts added in v0.1.0

func SliceToInts(v any) []int

SliceToInts any输入只能是一维slice或者数组

func SliceToString

func SliceToString(v any) []string

SliceToString any输入只能是一维slice或者数组

func Slope

func Slope(x1 int, y1 float64, x2 int, y2 float64) float64

Slope 计算斜率

func SlopeToDegrees added in v0.1.4

func SlopeToDegrees(m float64) float64

SlopeToDegrees 斜率转角度

func Sqrt

func Sqrt[T Number](v []T) []T

Sqrt 求平方根

func Std

func Std[T BaseType](x []T) T

Std 计算标准差

func StringIsFalse

func StringIsFalse(s string) bool

func StringIsNaN

func StringIsNaN(s string) bool

StringIsNaN 判断字符串是否NaN

func StringIsTrue

func StringIsTrue(s string) bool

func Sub

func Sub[T Number](x []T, y any) []T

Sub arithmetics 减法 z = x - y

func SubInplace added in v0.1.3

func SubInplace[T Number](x []T, y any) []T

SubInplace 减法 x = x - y

func Sum

func Sum[E Number](x []E) E

Sum 求和

func Transpose2D

func Transpose2D[T Number](x [][]T) [][]T

Transpose2D 矩阵转置

func TriangleBevel

func TriangleBevel(slope float64, x1 int, y1 float64, xn int) float64

TriangleBevel 三角形斜边

func TypeDefault

func TypeDefault[T BaseType]() T

TypeDefault 设定泛型默认值, 0或者NaN

func TypeError added in v0.0.3

func TypeError(tv any) error

TypeError 类型错误

func UnaryOperations

func UnaryOperations[T Number](x []T, f32 func([]float32) []float32, f64 func([]float64) []float64, cany func([]T) []T) []T

UnaryOperations 一元运算 unary operations

func UnaryOperations1

func UnaryOperations1[T Number](x []T, f32 func([]float32) float32, f64 func([]float64) float64, cany func([]T) T) T

func UnaryOperations2

func UnaryOperations2[T Number, E Number](x []T, f32 func([]float32) E, f64 func([]float64) E, cany func([]T) E) E

UnaryOperations2 一元运算 unary operations

运算和返回值是两种类型

func V2Diff deprecated added in v0.1.3

func V2Diff[T BaseType](s []T, param any) []T

Deprecated: 推荐使用Diff [wangfeng on 2024/2/22 17:51]

func Variance added in v0.2.9

func Variance(x []float64) float64

Variance 计算方差

func Where

func Where[T StatType](condition []T, x, y []T) []T

Where 返回根据“条件”从“x”或“y”中选择的元素 这里先实现一个简单的, 留给于总重构 params只支持两个默认值x和y, 如果condition为true返回x, 否则返回y condition和param都可能是基础数据类型,也可能是一个slice, 并且长度可能不一致 直接写成序列版本, 可能更简单

func Zeros

func Zeros[T BaseType](shape int) []T

Zeros Return a new array of given shape and type, filled with zeros.

args[0] dtype 基础数据类型

func ZscoreToConfidenceInterval

func ZscoreToConfidenceInterval(zScore float64) (confidenceInterval float64)

ZscoreToConfidenceInterval 通过分值查找置信区间

Types

type Array

type Array interface {
	Values() any // 保持原类型
}

Array 获取any类型切片数据

type BaseType

type BaseType interface {
	Integer | Float | ~string | ~bool
}

BaseType 基础类型

type BigFloat

type BigFloat = big.Float // 预留将来可能扩展float

type Complex

type Complex interface {
	~complex64 | ~complex128
}

Complex is a constraint that permits any complex numeric type. If future releases of Go add new predeclared complex numeric types, this constraint will be modified to include them.

type DType

type DType = float64

func Any2DType

func Any2DType(v any) DType

Any2DType any转DType

func Median

func Median[T Number](values []T) DType

Median returns median value of series. Linear interpolation is used for odd length.

中间值
TODO:未加验证,

func NaN

func NaN() DType

NaN DType

func PolyFit

func PolyFit(x, y []DType, deg int, args ...any) []DType

PolyFit

Least squares polynomial fit.

.. note::
	This forms part of the old polynomial API. Since version 1.4, the
	new polynomial API defined in `numpy.polynomial` is preferred.
	A summary of the differences can be found in the
	:doc:`transition guide </reference/routines.polynomials>`.

Fit a polynomial ``p(x) = p[0] * x**deg + ... + p[deg]`` of degree `deg`
to points `(x, y)`. Returns a vector of coefficients `p` that minimises
the squared error in the order `deg`, `deg-1`, ... `0`.

The `Polynomial.fit <numpy.polynomial.polynomial.Polynomial.fit>` class
method is recommended for new code as it is more stable numerically. See
the documentation of the method for more information.

Parameters
----------
x : array_like, shape (M,)
	x-coordinates of the M sample points ``(x[i], y[i])``.
y : array_like, shape (M,) or (M, K)
	y-coordinates of the sample points. Several data sets of sample
	points sharing the same x-coordinates can be fitted at once by
	passing in a 2D-array that contains one dataset per column.
deg : int
	Degree of the fitting polynomial

Returns
-------
p : ndarray, shape (deg + 1,) or (deg + 1, K)
	Polynomial coefficients, highest power first.  If `y` was 2-D, the
	coefficients for `k`-th data set are in ``p[:,k]``.

residuals, rank, singular_values, rcond
	These values are only returned if ``full == True``

	- residuals -- sum of squared residuals of the least squares fit
	- rank -- the effective rank of the scaled Vandermonde
		coefficient matrix
	- singular_values -- singular values of the scaled Vandermonde
		coefficient matrix
	- rcond -- value of `rcond`.

	For more details, see `numpy.linalg.lstsq`.

Warns
-----
RankWarning
	The rank of the coefficient matrix in the least-squares fit is
	deficient. The warning is only raised if ``full == False``.

	The warnings can be turned off by

	>>> import warnings
	>>> warnings.simplefilter('ignore', np.RankWarning)

See Also
--------
polyval : Compute polynomial values.
linalg.lstsq : Computes a least-squares fit.
scipy.interpolate.UnivariateSpline : Computes spline fits.

Notes
-----
The solution minimizes the squared error

.. math::
	E = \\sum_{j=0}^k |p(x_j) - y_j|^2

in the equations::

	x[0]**n * p[0] + ... + x[0] * p[n-1] + p[n] = y[0]
	x[1]**n * p[0] + ... + x[1] * p[n-1] + p[n] = y[1]
	...
	x[k]**n * p[0] + ... + x[k] * p[n-1] + p[n] = y[k]

The coefficient matrix of the coefficients `p` is a Vandermonde matrix.

`polyfit` issues a `RankWarning` when the least-squares fit is badly
conditioned. This implies that the best fit is not well-defined due
to numerical error. The results may be improved by lowering the polynomial
degree or by replacing `x` by `x` - `x`.mean(). The `rcond` parameter
can also be set to a value smaller than its default, but the resulting
fit may be spurious: including contributions from the small singular
values can add numerical noise to the result.

Note that fitting polynomial coefficients is inherently badly conditioned
when the degree of the polynomial is large or the interval of sample points
is badly centered. The quality of the fit should always be checked in these
cases. When polynomial fits are not satisfactory, splines may be a good
alternative.

References
----------
.. [1] Wikipedia, "Curve fitting",
		https://en.wikipedia.org/wiki/Curve_fitting
.. [2] Wikipedia, "Polynomial interpolation",
		https://en.wikipedia.org/wiki/Polynomial_interpolation
.. [3] numpy.polyfit(x, y, deg, rcond=None, full=False, w=None, cov=False)
		https://numpy.org/doc/stable/reference/generated/numpy.polyfit.html

Examples
--------
>>> import warnings
>>> x = np.array([0.0, 1.0, 2.0, 3.0,  4.0,  5.0])
>>> y = np.array([0.0, 0.8, 0.9, 0.1, -0.8, -1.0])
>>> z = np.polyfit(x, y, 3)
>>> z
array([ 0.08703704, -0.81349206,  1.69312169, -0.03968254]) # may vary

func PolyVal

func PolyVal(p, x []DType) []DType

PolyVal

Evaluate a polynomial at specific values.

.. note::
This forms part of the old polynomial API. Since version 1.4, the
new polynomial API defined in `numpy.polynomial` is preferred.
A summary of the differences can be found in the
:doc:`transition guide </reference/routines.polynomials>`.

If `p` is of length N, this function returns the value:

``p[0]*x**(N-1) + p[1]*x**(N-2) + ... + p[N-2]*x + p[N-1]``

If `x` is a sequence, then ``p(x)`` is returned for each element of ``x``.
If `x` is another polynomial then the composite polynomial ``p(x(t))``
is returned.

Parameters

----------

p : array_like or poly1d object
	1D array of polynomial coefficients (including coefficients equal
	to zero) from highest degree to the constant term, or an
	instance of poly1d.
x : array_like or poly1d object
	A number, an array of numbers, or an instance of poly1d, at
	which to evaluate `p`.

Returns

-------

values : ndarray or poly1d
	If `x` is a poly1d instance, the result is the composition of the two
	polynomials, i.e., `x` is "substituted" in `p` and the simplified
	result is returned. In addition, the type of `x` - array_like or
	poly1d - governs the type of the output: `x` array_like => `values`
	array_like, `x` a poly1d object => `values` is also.

See Also
--------
poly1d: A polynomial class.

Notes
-----
Horner's scheme [1]_ is used to evaluate the polynomial. Even so,
for polynomials of high degree the values may be inaccurate due to
rounding errors. Use carefully.

If `x` is a subtype of `ndarray` the return value will be of the same type.

References
----------
.. [1] I. N. Bronshtein, K. A. Semendyayev, and K. A. Hirsch (Eng.
trans. Ed.), *Handbook of Mathematics*, New York, Van Nostrand
Reinhold Co., 1985, pg. 720.

Examples
--------
>>> np.polyval([3,0,1], 5)  # 3 * 5**2 + 0 * 5**1 + 1
76
>>> np.polyval([3,0,1], np.poly1d(5))
poly1d([76])
>>> np.polyval(np.poly1d([3,0,1]), 5)
76
>>> np.polyval(np.poly1d([3,0,1]), np.poly1d(5))
poly1d([76])

func Slice2DType

func Slice2DType(v any) []DType

Slice2DType 切片转DType

type DTypeArray added in v0.0.7

type DTypeArray interface {
	DTypes() []DType // to dtype
}

DTypeArray 获取DType切片的接口

type DataPoint added in v0.2.2

type DataPoint struct {
	X int     // Y切片的索引
	Y float64 // 值
}

DataPoint 数据点, X轴为时间类切片的索引, Y轴为具体数值

func (DataPoint) ToPoint added in v0.2.2

func (this DataPoint) ToPoint() Point

type Float

type Float interface {
	~float32 | ~float64
}

Float is a constraint that permits any floating-point type. If future releases of Go add new predeclared floating-point types, this constraint will be modified to include them.

type GenericType

type GenericType interface {
	~bool | ~int32 | ~int64 | ~int | ~float32 | ~float64 | ~string
}

GenericType Series支持的所有类型 Deprecated: 不推荐使用

type Integer

type Integer interface {
	Signed | Unsigned
}

Integer is a constraint that permits any integer type. If future releases of Go add new predeclared integer types, this constraint will be modified to include them.

type Line added in v0.1.4

type Line struct {
	// contains filtered or unexported fields
}

Line LineEquation 线性方程式

① Ax + By + C = 0
② 斜率k = -(A/B)
③ x截距 = -(C/A), y截距 = -(C/B)

func CalculateLineEquation added in v0.1.4

func CalculateLineEquation(point1, point2 Point) Line

CalculateLineEquation 已知两个点, 计算线性方程式

func (Line) Analyze added in v0.2.6

func (this Line) Analyze(data []float64, digits int) (X, Y []float64, tendency []LinerTrend)

Analyze 分析线性趋势

func (Line) Angle added in v0.2.6

func (this Line) Angle(other Line) float64

Angle 计算两条直线之间的角度

func (Line) Degrees added in v0.1.4

func (this Line) Degrees() float64

Degrees 计算角度

func (Line) Distance added in v0.1.4

func (this Line) Distance(p Point) float64

Distance 点到线的距离

                         ___________
公式 |(Ax0 + By0 + C)| / √(A^2 + B^2)

func (Line) Equation added in v0.1.4

func (this Line) Equation() (A, B, C float64)

Equation 返回方程式 A, B, C

func (Line) Extend added in v0.1.8

func (this Line) Extend(data []float64, digits int) (X, Y []float64, tendency int)

Extend 延伸线

func (Line) HorizontalDistance added in v0.1.8

func (this Line) HorizontalDistance(p Point) float64

HorizontalDistance 水平方向距离

p点到线的水平方向上的距离

func (Line) Incr added in v0.1.8

func (this Line) Incr(n int) (x, y float64)

Incr 增量方式得出line延伸的x轴和y轴

func (Line) ParallelLine added in v0.1.4

func (this Line) ParallelLine(p Point) Line

ParallelLine 通过 一个点的y轴坐标计算一个新的平行线

func (Line) Radian added in v0.1.4

func (this Line) Radian() float64

Radian 弧度

func (Line) ShortestDistance added in v0.1.8

func (this Line) ShortestDistance(other Line) float64

ShortestDistance 计算 与另外一条直线的最短距离

func (Line) SymmetricParallelLine added in v0.1.4

func (this Line) SymmetricParallelLine(p Point) Line

SymmetricParallelLine 计算 点对称(等距离)的平行线

func (Line) VerticalDistance added in v0.1.8

func (this Line) VerticalDistance(p Point) float64

VerticalDistance 垂直方向距离

p点到线的垂直方向上的距离

func (Line) X added in v0.1.8

func (this Line) X(y float64) float64

X 通过 y 轴坐标计算 x轴坐标

func (Line) Y added in v0.1.6

func (this Line) Y(x float64) float64

Y 通过 x 轴坐标计算 y轴坐标

type LinerTrend added in v0.1.9

type LinerTrend struct {
	X     int // 索引
	State int // 状态
}

LinerTrend 线性趋势

func Cross added in v0.1.8

func Cross[E Number](a, b []E) []LinerTrend

Cross 上穿和下穿

a 上穿或者下穿b的状态集合

type MoveType deprecated

type MoveType interface {
	StatType | ~bool | ~string
}

Deprecated: 已弃用

type Number

type Number interface {
	Integer | Float
}

Number int和uint的长度取决于CPU是多少位

type Number16 deprecated

type Number16 interface {
	~int16 | ~uint16
}

Deprecated: 不推荐使用

type Number32 deprecated

type Number32 interface {
	~int32 | ~uint32 | float32
}

Deprecated: 不推荐使用

type Number64 deprecated

type Number64 interface {
	~int64 | ~uint64 | float64 | int | uint
}

Deprecated: 不推荐使用

type Number8 deprecated

type Number8 interface {
	~int8 | ~uint8
}

Deprecated: 不推荐使用

type NumberOfCPUBitsRelated

type NumberOfCPUBitsRelated interface {
	~int | ~uint | ~uintptr
}

NumberOfCPUBitsRelated The number of CPU bits is related Deprecated: 不推荐使用

type Ordered

type Ordered interface {
	Integer | Float | ~string
}

Ordered is a constraint that permits any ordered type: any type that supports the operators < <= >= >. If future releases of Go add new ordered types, this constraint will be modified to include them.

type Periods added in v0.1.6

type Periods struct {
	Array []DType
	N     DType
}

Periods 周期

func AnyToPeriod added in v0.1.6

func AnyToPeriod(n any) Periods

AnyToPeriod any转周期

func (Periods) At added in v0.1.6

func (this Periods) At(i int) (n DType, good bool)

At 获取下标为i的元素

如果i超过切片V的长度, 则直接返回常量C
附带越界检查 boundaryExceeded

func (Periods) IsConst added in v0.1.6

func (this Periods) IsConst() bool

IsConst 是否全部常量

type Point added in v0.1.4

type Point struct {
	X float64 // x 轴
	Y float64 // y 轴
}

Point 点

func NewPoint added in v0.1.6

func NewPoint[T1 Number, T2 Number](x T1, y T2) Point

func (Point) Add added in v0.1.6

func (this Point) Add(p Point) Point

func (Point) ToDataPoint added in v0.2.2

func (this Point) ToDataPoint() DataPoint

type QuantizationFactor added in v0.1.4

type QuantizationFactor interface {
	// Normalize 归一化, 标准化, 数据预处理
	Normalize()
}

QuantizationFactor 量化因子接口

type Signed

type Signed interface {
	~int | ~int8 | ~int16 | ~int32 | ~int64
}

Signed is a constraint that permits any signed integer type. If future releases of Go add new predeclared signed integer types, this constraint will be modified to include them.

type StatType

type StatType interface {
	~int32 | ~int64 | ~float32 | ~float64
}

StatType 可以统计的类型 Deprecated: 不推荐使用

type StringFormatter

type StringFormatter func(val any) string

StringFormatter is used to convert a value into a string. Val can be nil or the concrete type stored by the series.

type Unsigned

type Unsigned interface {
	~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr
}

Unsigned is a constraint that permits any unsigned integer type. If future releases of Go add new predeclared unsigned integer types, this constraint will be modified to include them.

type Window deprecated added in v0.1.0

type Window[E Number] struct {
	V []E // 切片
	C E   // 常量
}

Window 参数N的新方式

Deprecated: 推荐 Periods [wangfeng on 2024/2/26 09:50]

func Any2Window added in v0.1.3

func Any2Window[E Number](n any) Window[E]

func RollingWindow added in v0.1.0

func RollingWindow(v []DType, c DType) Window[DType]

func (Window[E]) At added in v0.1.0

func (this Window[E]) At(i int) E

At 获取下标为i的元素 如果i超过切片V的长度, 则直接返回常量C

func (Window[E]) IsConst added in v0.1.3

func (this Window[E]) IsConst() bool

IsConst 是否全部常量

Directories

Path Synopsis
asm
internal
constraints
Package constraints defines a set of useful constraints to be used with type parameters.
Package constraints defines a set of useful constraints to be used with type parameters.
rand
Package rand implements pseudo-random number generators.
Package rand implements pseudo-random number generators.
Package math32 provides basic constants and mathematical functions for float32 types.
Package math32 provides basic constants and mathematical functions for float32 types.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL