| | |
| | |
| | |
| |
|
| | package a |
| |
|
| | import ( |
| | "math" |
| | ) |
| |
|
| | type Numeric interface { |
| | ~int | ~int8 | ~int16 | ~int32 | ~int64 | |
| | ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr | |
| | ~float32 | ~float64 | |
| | ~complex64 | ~complex128 |
| | } |
| |
|
| | |
| | type numericAbs[T Numeric] interface { |
| | ~struct{ Value_ T } |
| | Abs() T |
| | Value() T |
| | } |
| |
|
| | |
| | |
| | func absDifference[T Numeric, U numericAbs[T]](a, b U) T { |
| | d := a.Value() - b.Value() |
| | dt := U{Value_: d} |
| | return dt.Abs() |
| | } |
| |
|
| | |
| | type orderedNumeric interface { |
| | ~int | ~int8 | ~int16 | ~int32 | ~int64 | |
| | ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr | |
| | ~float32 | ~float64 |
| | } |
| |
|
| | |
| | type Complex interface { |
| | ~complex64 | ~complex128 |
| | } |
| |
|
| | |
| | |
| | type orderedAbs[T orderedNumeric] struct { |
| | Value_ T |
| | } |
| |
|
| | func (a orderedAbs[T]) Abs() T { |
| | if a.Value_ < 0 { |
| | return -a.Value_ |
| | } |
| | return a.Value_ |
| | } |
| |
|
| | |
| | |
| | |
| | |
| |
|
| | func (a orderedAbs[T]) Value() T { |
| | return a.Value_ |
| | } |
| |
|
| | |
| | |
| | type complexAbs[T Complex] struct { |
| | Value_ T |
| | } |
| |
|
| | func realimag(x any) (re, im float64) { |
| | switch z := x.(type) { |
| | case complex64: |
| | re = float64(real(z)) |
| | im = float64(imag(z)) |
| | case complex128: |
| | re = real(z) |
| | im = imag(z) |
| | default: |
| | panic("unknown complex type") |
| | } |
| | return |
| | } |
| |
|
| | func (a complexAbs[T]) Abs() T { |
| | |
| | r, i := realimag(a.Value_) |
| | |
| | |
| | d := math.Sqrt(r*r + i*i) |
| | return T(complex(d, 0)) |
| | } |
| |
|
| | func (a complexAbs[T]) Value() T { |
| | return a.Value_ |
| | } |
| |
|
| | |
| | |
| | func OrderedAbsDifference[T orderedNumeric](a, b T) T { |
| | return absDifference(orderedAbs[T]{a}, orderedAbs[T]{b}) |
| | } |
| |
|
| | |
| | |
| | func ComplexAbsDifference[T Complex](a, b T) T { |
| | return absDifference(complexAbs[T]{a}, complexAbs[T]{b}) |
| | } |
| |
|