compact_float

package module
v1.6.3 Latest Latest
Warning

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

Go to latest
Published: Oct 4, 2023 License: MIT Imports: 9 Imported by: 3 modules, 12 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Compact Float

A go implementation of compact float.

Library Usage


import (
	"fmt"

	"github.com/cockroachdb/apd/v2"
	"github.com/kstenerud/go-compact-float"
)

func demonstrateEncodeDecodeDFloat() {
	originalValue := DFloat{
		Exponent:    100,
		Coefficient: 863994506,
	}

	buffer := &bytes.Buffer{}
	_, err := Encode(originalValue, buffer)
	if err != nil {
		// TODO: Handle error
	}
	fmt.Printf("%v encoded = %v\n", originalValue, buffer.Bytes())

	fmt.Printf("%v decoded ", buffer.Bytes())
	value, _, bytesDecoded, err := Decode(buffer)
	if err != nil {
		// TODO: Handle error
	}
	fmt.Printf("(%v bytes) = %v\n", bytesDecoded, value)

	// Prints:
	// 8.63994506e+108 encoded = [144 3 138 133 254 155 3]
	// [144 3 138 133 254 155 3] decoded (7 bytes) = 8.63994506e+108
}

func demonstrateEncodeDecodeBig() {
	// This value is too big to fit into a float64 or DFloat.
	originalValue, _, err := apd.NewFromString("-9.4452837206285466345998345667683453466347345e-5000")
	if err != nil {
		// TODO: Handle error
	}

	buffer := &bytes.Buffer{}
	if _, err = EncodeBig(originalValue, buffer); err != nil {
		// TODO: Handle error
	}
	fmt.Printf("%v encoded = %v\n", originalValue, buffer.Bytes())

	fmt.Printf("%v decoded ", buffer.Bytes())
	_, bigValue, bytesDecoded, err := Decode(buffer)
	if err != nil {
		// TODO: Handle error
	}
	fmt.Printf("(%v bytes) = %v\n", bytesDecoded, bigValue)

	// Prints:
	// -9.4452837206285466345998345667683453466347345E-5000 encoded = [207 157 1 209 142 162 230 131 138 191 193 187 225 243 223 252 238 172 229 254 225 143 226 67]
	// [207 157 1 209 142 162 230 131 138 191 193 187 225 243 223 252 238 172 229 254 225 143 226 67] decoded (24 bytes) = -9.4452837206285466345998345667683453466347345E-5000
}

func demonstrateEncodeDecodeFloat64() {
	originalValue := 0.1473445219134543
	significantDigits := 6
	buffer := &bytes.Buffer{}
	value, err := DFloatFromFloat64(originalValue, significantDigits)
	if err != nil {
		// TODO: Handle error (which might be RoundingError, in which case value is the rounded result)
	}
	_, err = Encode(value, buffer)
	if err != nil {
		// TODO: Handle error
	}
	fmt.Printf("%v encoded using %d significant digits = %v\n", originalValue, significantDigits, buffer.Bytes())

	fmt.Printf("%v decoded ", buffer.Bytes())
	decodedValue, _, bytesDecoded, err := Decode(buffer)
	if err != nil {
		// TODO: Handle error
	}
	fmt.Printf("(%v bytes) = %v\n", bytesDecoded, decodedValue.Float())

	// Prints:
	// 0.1473445219134543 encoded using 6 significant digits = [26 145 255 8]
	// [26 145 255 8] decoded (4 bytes) = 0.147345
}

License

MIT License:

Copyright 2019 Karl Stenerud

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Documentation

Index

Constants

View Source
const (
	CoeffNegativeZero     = 0
	CoeffInfinity         = 1
	CoeffNegativeInfinity = 5
	CoeffNan              = 2
	CoeffSignalingNan     = 6
)
View Source
const ExpSpecial = int32(-0x80000000)

An exponent value of ExpSpecial indicates that this is a special value. The coefficient will be a special code that determines what special value is represented (CoeffInfinity, CoeffNan, etc).

Variables

View Source
var ErrorIncomplete = fmt.Errorf("Compact float value is incomplete")

Functions

func Encode

func Encode(value DFloat, writer io.Writer) (bytesEncoded int, err error)

Encodes a DFloat to a writer.

func EncodeBig added in v1.3.0

func EncodeBig(value *apd.Decimal, writer io.Writer) (bytesEncoded int, err error)

Encodes an apd.Decimal to a writer.

func EncodeBigToBytes added in v1.5.0

func EncodeBigToBytes(value *apd.Decimal, buffer []byte) (bytesEncoded int)

Encodes an apt.Decimal to a buffer. Assumes the buffer is big enough (see MaxEncodeLengthBig()).

func EncodeInfinity added in v1.2.1

func EncodeInfinity(buffer []byte) (bytesEncoded int)

Encodes positive infinity, using 2 bytes.

func EncodeNegativeInfinity added in v1.3.1

func EncodeNegativeInfinity(buffer []byte) (bytesEncoded int)

Encodes negative infinity, using 2 bytes.

func EncodeNegativeZero added in v1.3.1

func EncodeNegativeZero(buffer []byte) (bytesEncoded int)

Encodes negative zero, using 1 byte.

func EncodeQuietNan added in v1.3.1

func EncodeQuietNan(buffer []byte) (bytesEncoded int)

Encodes a quiet NaN, using 2 bytes.

func EncodeSignalingNan added in v1.3.1

func EncodeSignalingNan(buffer []byte) (bytesEncoded int)

Encodes a signaling NaN, using 2 bytes.

func EncodeToBytes added in v1.5.0

func EncodeToBytes(value DFloat, buffer []byte) (bytesEncoded int)

Encodes a DFloat to a byte buffer. Assumes the buffer is big enough (see MaxEncodeLength()).

func EncodeZero added in v1.2.1

func EncodeZero(buffer []byte) (bytesEncoded int)

Encodes positive zero, using 1 byte.

func MaxEncodeLength added in v1.1.0

func MaxEncodeLength() int

Maximum number of bytes required to encode a DFloat.

func MaxEncodeLengthBig added in v1.3.4

func MaxEncodeLengthBig(value *apd.Decimal) int

Maximum number of bytes required to encode a particular apd.Decimal. This is an estimate; it may be smaller, but never bigger.

func RoundingError added in v1.6.0

func RoundingError() error

Types

type DFloat added in v1.3.0

type DFloat struct {
	Exponent    int32
	Coefficient int64
}

DFloat represents a decimal floating point value in 96 bits. It supports coefficient values within the range of int64, and exponent values from -0x7fffffff to 0x7fffffff. The exponent -0x80000000 (ExpSpecial) is used to indicate special values, and is not allowed as an actual exponent value.

func DFloatFromAPD added in v1.3.0

func DFloatFromAPD(value *apd.Decimal) (DFloat, error)

Convert an apd.Decimal to DFloat. If the value is too big to fit, its lower significant digits will be rounded (half-to-even) and RoundingError will be returned along with the rounded value.

func DFloatFromBigFloat added in v1.4.6

func DFloatFromBigFloat(value *big.Float) (DFloat, error)

Convert a big.Float to DFloat. If the value is too big to fit, its lower significant digits will be rounded (half-to-even) and RoundingError will be returned along with the rounded value.

func DFloatFromBigInt added in v1.3.5

func DFloatFromBigInt(value *big.Int) (DFloat, error)

Convert a big.Int to DFloat. If the value is too big to fit, its lower significant digits will be rounded (half-to-even) and RoundingError will be returned along with the rounded value.

func DFloatFromFloat64 added in v1.3.0

func DFloatFromFloat64(value float64, significantDigits int) (DFloat, error)

Convert an iee754 binary floating point value to DFloat, with the specified number of significant digits. Rounding is half-to-even, meaning it rounds towards an even number when exactly halfway. If rounding occurs, the returned error will be RoundingError. If significantDigits is less than 1, no rounding takes place.

func DFloatFromString added in v1.3.0

func DFloatFromString(str string) (DFloat, error)

Convert a string float representation to DFloat. If the value is too big to fit, its lower significant digits will be rounded (half-to-even) and RoundingError will be returned along with the rounded value.

func DFloatFromUInt added in v1.3.5

func DFloatFromUInt(value uint64) (DFloat, error)

Convert an unsigned int to DFloat. If the value is too big to fit, its lowest significant digit will be rounded (half-to-even) and RoundingError will be returned along with the rounded value.

func DFloatValue added in v1.3.0

func DFloatValue(exponent int32, coefficient int64) DFloat

func Decode

func Decode(reader io.Reader) (value DFloat, bigValue *apd.Decimal, bytesDecoded int, err error)

Decode a float. bigValue will be nil unless the decoded value is too big to fit into a DFloat.

func DecodeWithByteBuffer added in v1.5.0

func DecodeWithByteBuffer(reader io.Reader, buffer []byte) (value DFloat, bigValue *apd.Decimal, bytesDecoded int, err error)

Decode a float using the supplied single-byte buffer. bigValue will be nil unless the decoded value is too big to fit into a DFloat.

func Infinity added in v1.3.2

func Infinity() DFloat

func NegativeInfinity added in v1.3.2

func NegativeInfinity() DFloat

func NegativeZero added in v1.3.2

func NegativeZero() DFloat

func QuietNaN added in v1.3.2

func QuietNaN() DFloat

func SignalingNaN added in v1.3.2

func SignalingNaN() DFloat

func Zero added in v1.3.2

func Zero() DFloat

func (DFloat) APD added in v1.3.0

func (this DFloat) APD() *apd.Decimal

Returns the apd.Decimal representation of this value. All DFloat values can be represented as apd.Decimal.

func (DFloat) BigFloat added in v1.4.6

func (this DFloat) BigFloat() *big.Float

func (DFloat) BigInt added in v1.4.3

func (this DFloat) BigInt() (*big.Int, error)

Returns the big.Int representation of this value. Returns an error if the value is not a whole number.

func (DFloat) Float added in v1.3.0

func (this DFloat) Float() float64

Returns the float64 representation of this value. The result will be rounded according to strconv.ParseFloat() if it doesn't fit.

func (DFloat) Int added in v1.4.1

func (this DFloat) Int() (int64, error)

Returns the int64 representation of this value. Returns an error if the value cannot fit.

func (DFloat) IsInfinity added in v1.3.0

func (this DFloat) IsInfinity() bool

Returns true if the value is positive or negative infinity

func (DFloat) IsNan added in v1.3.0

func (this DFloat) IsNan() bool

Returns true if the value is a quiet or signaling NaN

func (DFloat) IsNegativeInfinity added in v1.3.0

func (this DFloat) IsNegativeInfinity() bool

func (DFloat) IsNegativeZero added in v1.3.0

func (this DFloat) IsNegativeZero() bool

func (DFloat) IsSignalingNan added in v1.3.0

func (this DFloat) IsSignalingNan() bool

func (DFloat) IsSpecial added in v1.3.0

func (this DFloat) IsSpecial() bool

func (DFloat) IsZero added in v1.3.0

func (this DFloat) IsZero() bool

Returns true if the value is positive or negative zero

func (DFloat) String added in v1.3.0

func (this DFloat) String() string

func (DFloat) Text added in v1.3.3

func (this DFloat) Text(format byte) string

Text converts the floating-point number x to a string according to the given format. The format is one of:

'e'	-d.dddde±dd, decimal exponent, exponent digits
'E'	-d.ddddE±dd, decimal exponent, exponent digits
'f'	-ddddd.dddd, no exponent
'g'	like 'e' for large exponents, like 'f' otherwise
'G'	like 'E' for large exponents, like 'f' otherwise

If format is a different character, Text returns a "%" followed by the unrecognized.Format character. The 'f' format has the possibility of displaying precision that is not present in the Decimal when it appends zeros. All other formats always show the exact precision of the Decimal.

This method call is forwarded to *apd.Decimal.Text()

func (DFloat) Uint added in v1.4.1

func (this DFloat) Uint() (uint64, error)

Returns the uint64 representation of this value. Returns an error if the value cannot fit.

Jump to

Keyboard shortcuts

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