-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfloat16.go
More file actions
429 lines (370 loc) · 12 KB
/
float16.go
File metadata and controls
429 lines (370 loc) · 12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
// Package float16 implements both 16-bit floating point data types:
// - Float16: IEEE 754-2008 half-precision (1 sign, 5 exponent, 10 mantissa bits)
// - BFloat16: "Brain Floating Point" format (1 sign, 8 exponent, 7 mantissa bits)
//
// This implementation provides conversion between both types and other floating-point types
// (float32 and float64) with support for various rounding modes and error handling.
//
// # Special Values
//
// The float16 type supports all IEEE 754-2008 special values:
// - Positive and negative zero
// - Positive and negative infinity
// - Not-a-Number (NaN) values with payload
// - Normalized numbers
// - Subnormal (denormal) numbers
//
// # Subnormal Numbers
//
// When converting to higher-precision types (float32/float64), subnormal float16 values
// are preserved. However, when converting back from higher-precision types to float16,
// subnormal values may be rounded to the nearest representable normal float16 value.
// This behavior is consistent with many hardware implementations that handle subnormals
// in a similar way for performance reasons.
//
// # Rounding Modes
//
// The following rounding modes are supported for conversions:
// - RoundNearestEven: Round to nearest, ties to even (default)
// - RoundTowardZero: Round toward zero (truncate)
// - RoundTowardPositive: Round toward positive infinity
// - RoundTowardNegative: Round toward negative infinity
// - RoundNearestAway: Round to nearest, ties away from zero
//
// # Error Handling
//
// Conversion functions with a ConversionMode parameter can return errors for:
// - Overflow: When a value is too large to be represented
// - Underflow: When a value is too small to be represented (in strict mode)
// - Inexact: When rounding occurs (in strict mode)
//
// See: http://en.wikipedia.org/wiki/Half-precision_floating-point_format
package float16
import (
"math"
"sync"
)
// Package version information
const (
Version = "1.0.0"
VersionMajor = 1
VersionMinor = 0
VersionPatch = 0
)
var (
DefaultConversionMode ConversionMode = ModeIEEE
DefaultRoundingMode RoundingMode = RoundNearestEven
)
// Package configuration
type Config struct {
DefaultConversionMode ConversionMode
DefaultRoundingMode RoundingMode
DefaultArithmeticMode ArithmeticMode
EnableFastMath bool // Package float16 implements the 16-bit floating point data type (IEEE 754-2008).
// This implementation provides conversion between float16 and other floating-point types
// (float32 and float64) with support for various rounding modes and error handling.
//
// # Special Values
//
// The float16 type supports all IEEE 754-2008 special values:
// - Positive and negative zero
// - Positive and negative infinity
// - Not-a-Number (NaN) values with payload
// - Normalized numbers
// - Subnormal (denormal) numbers
//
// # Subnormal Numbers
//
// When converting to higher-precision types (float32/float64), subnormal float16 values
// are preserved. However, when converting back from higher-precision types to float16,
// subnormal values may be rounded to the nearest representable normal float16 value.
// This behavior is consistent with many hardware implementations that handle subnormals
// in a similar way for performance reasons.
//
// # Rounding Modes
//
// The following rounding modes are supported for conversions:
// - RoundNearestEven: Round to nearest, ties to even (default)
// - RoundTowardZero: Round toward zero (truncate)
// - RoundTowardPositive: Round toward positive infinity
// - RoundTowardNegative: Round toward negative infinity
// - RoundNearestAway: Round to nearest, ties away from zero
//
// # Error Handling
//
// Conversion functions with a ConversionMode parameter can return errors for:
// - Overflow: When a value is too large to be represented
// - Underflow: When a value is too small to be represented (in strict mode)
// - Inexact: When rounding occurs (in strict mode)
//
// See: http://en.wikipedia.org/wiki/Half-precision_floating-point_format
}
// DefaultConfig returns the default package configuration
func DefaultConfig() *Config {
return &Config{
DefaultConversionMode: DefaultConversionMode,
DefaultRoundingMode: DefaultRoundingMode,
DefaultArithmeticMode: ModeIEEEArithmetic,
EnableFastMath: false,
}
}
var (
configMutex sync.RWMutex
config = DefaultConfig()
)
// Configure applies the given configuration to the package
func Configure(cfg *Config) {
configMutex.Lock()
defer configMutex.Unlock()
config = cfg
DefaultConversionMode = cfg.DefaultConversionMode
DefaultRoundingMode = cfg.DefaultRoundingMode
DefaultArithmeticMode = cfg.DefaultArithmeticMode
}
// GetConfig returns the current package configuration
func GetConfig() *Config {
configMutex.RLock()
defer configMutex.RUnlock()
// Return a copy to prevent external modification
return &Config{
DefaultConversionMode: config.DefaultConversionMode,
DefaultRoundingMode: config.DefaultRoundingMode,
DefaultArithmeticMode: config.DefaultArithmeticMode,
EnableFastMath: config.EnableFastMath,
}
}
// GetVersion returns the package version string
func GetVersion() string {
return Version
}
// Convenience functions for common operations
// Zero returns a Float16 zero value
func Zero() Float16 {
return PositiveZero
}
// One returns a Float16 value representing 1.0
func One() Float16 {
return FromFloat32(1.0)
}
// NaN returns a Float16 quiet NaN value
func NaN() Float16 {
return QuietNaN
}
// Inf returns a Float16 infinity value
// If sign >= 0, returns positive infinity
// If sign < 0, returns negative infinity
func Inf(sign int) Float16 {
if sign >= 0 {
return PositiveInfinity
}
return NegativeInfinity
}
// IsInf reports whether f is an infinity, according to sign
// If sign > 0, IsInf reports whether f is positive infinity
// If sign < 0, IsInf reports whether f is negative infinity
// If sign == 0, IsInf reports whether f is either infinity
func IsInf(f Float16, sign int) bool {
return f.IsInf(sign)
}
// IsNaN reports whether f is an IEEE 754 "not-a-number" value
func IsNaN(f Float16) bool {
return f.IsNaN()
}
// Signbit reports whether f is negative or negative zero
func Signbit(f Float16) bool {
return f.Signbit()
}
// Utility functions for working with Float16 values
// NextAfter returns the next representable Float16 value after f in the direction of g
func NextAfter(f, g Float16) Float16 {
if f.IsNaN() || g.IsNaN() {
return QuietNaN
}
if Equal(f, g) {
return g
}
if f.IsZero() {
if g.Signbit() {
return FromBits(0x8001) // Smallest negative subnormal
}
return FromBits(0x0001) // Smallest positive subnormal
}
bits := f.Bits()
if (f.ToFloat32() < g.ToFloat32()) == !f.Signbit() {
bits++
} else {
bits--
}
return FromBits(bits)
}
// Frexp breaks f into a normalized fraction and an integral power of two
// It returns frac and exp satisfying f == frac × 2^exp, with the absolute
// value of frac in the interval [0.5, 1) or zero
func Frexp(f Float16) (frac Float16, exp int) {
if f.IsZero() || f.IsNaN() || f.IsInf(0) {
return f, 0
}
f32 := f.ToFloat32()
frac32, exp := math.Frexp(float64(f32))
return FromFloat32(float32(frac32)), exp
}
// Ldexp returns frac × 2^exp
func Ldexp(frac Float16, exp int) Float16 {
if frac.IsZero() || frac.IsNaN() || frac.IsInf(0) {
return frac
}
frac32 := frac.ToFloat32()
result := math.Ldexp(float64(frac32), exp)
return FromFloat32(float32(result))
}
// Modf returns integer and fractional floating-point numbers that sum to f
// Both values have the same sign as f
func Modf(f Float16) (integer, frac Float16) {
if f.IsNaN() || f.IsInf(0) {
return f, f
}
f32 := f.ToFloat32()
int32, frac32 := math.Modf(float64(f32))
return FromFloat32(float32(int32)), FromFloat32(float32(frac32))
}
// Validation and classification functions
// IsFinite reports whether f is neither infinite nor NaN
func IsFinite(f Float16) bool {
return f.IsFinite()
}
// IsNormal reports whether f is a normal number (not zero, subnormal, infinite, or NaN)
func IsNormal(f Float16) bool {
return f.IsNormal()
}
// IsSubnormal reports whether f is a subnormal number
func IsSubnormal(f Float16) bool {
return f.IsSubnormal()
}
// FpClassify returns the IEEE 754 class of f
func FpClassify(f Float16) FloatClass {
return f.Class()
}
// Performance monitoring and debugging
// GetMemoryUsage returns the current memory usage of the package in bytes
func GetMemoryUsage() int {
// Float16 package uses minimal memory (no lookup tables)
// Only constants and code, estimated at ~8KB
return 8192
}
// DebugInfo returns debugging information about the package state
func DebugInfo() map[string]interface{} {
cfg := GetConfig()
return map[string]interface{}{
"version": Version,
"memory_usage_bytes": GetMemoryUsage(),
"default_conversion_mode": cfg.DefaultConversionMode,
"default_rounding_mode": cfg.DefaultRoundingMode,
"default_arithmetic_mode": cfg.DefaultArithmeticMode,
"fast_math_enabled": cfg.EnableFastMath,
"ieee754_compliant": true,
"supports_subnormals": true,
"lookup_tables": false,
}
}
// Benchmark helpers for performance testing
// BenchmarkOperation represents a benchmarkable operation
type BenchmarkOperation func(Float16, Float16) Float16
// GetBenchmarkOperations returns a map of operations suitable for benchmarking
func GetBenchmarkOperations() map[string]BenchmarkOperation {
return map[string]BenchmarkOperation{
"Add": Add,
"Sub": Sub,
"Mul": Mul,
"Div": Div,
}
}
// Constants for common values
var (
// Common integer values
Zero16 = PositiveZero
One16 = FromFloat32(1.0)
Two16 = FromFloat32(2.0)
Three16 = FromFloat32(3.0)
Four16 = FromFloat32(4.0)
Five16 = FromFloat32(5.0)
Ten16 = FromFloat32(10.0)
// Common fractional values
Half16 = FromFloat32(0.5)
Quarter16 = FromFloat32(0.25)
Third16 = FromFloat32(1.0 / 3.0)
// Special mathematical values
NaN16 = QuietNaN
PosInf = PositiveInfinity
NegInf = NegativeInfinity
// Commonly used constants
Deg2Rad = FromFloat32(float32(math.Pi / 180.0)) // Degrees to radians
Rad2Deg = FromFloat32(float32(180.0 / math.Pi)) // Radians to degrees
)
// Helper functions for slice operations with error handling
// ValidateSliceLength checks if two slices have the same length
func ValidateSliceLength(a, b []Float16) error {
if len(a) != len(b) {
return &Float16Error{
Op: "slice_operation",
Msg: "slice length mismatch",
Code: ErrInvalidOperation,
}
}
return nil
}
// SliceStats computes basic statistics for a Float16 slice
type SliceStats struct {
Min Float16
Max Float16
Sum Float16
Mean Float16
Length int
}
// ComputeSliceStats calculates statistics for a Float16 slice
func ComputeSliceStats(s []Float16) SliceStats {
if len(s) == 0 {
return SliceStats{}
}
stats := SliceStats{
Min: s[0],
Max: s[0],
Sum: PositiveZero,
Length: len(s),
}
for _, v := range s {
if !v.IsNaN() {
if Less(v, stats.Min) {
stats.Min = v
}
if Greater(v, stats.Max) {
stats.Max = v
}
}
stats.Sum = Add(stats.Sum, v)
}
if stats.Length > 0 {
stats.Mean = Div(stats.Sum, FromFloat32(float32(stats.Length)))
}
return stats
}
// Experimental features (may change in future versions)
// FastAdd performs addition optimized for speed (may sacrifice precision)
func FastAdd(a, b Float16) Float16 {
return FromFloat32(a.ToFloat32() + b.ToFloat32())
}
// FastMul performs multiplication optimized for speed (may sacrifice precision)
func FastMul(a, b Float16) Float16 {
return FromFloat32(a.ToFloat32() * b.ToFloat32())
}
// VectorAdd performs vectorized addition (placeholder for future SIMD implementation)
func VectorAdd(a, b []Float16) []Float16 {
// Currently just calls the regular slice operation
// Future versions may implement SIMD optimizations
return AddSlice(a, b)
}
// VectorMul performs vectorized multiplication (placeholder for future SIMD implementation)
func VectorMul(a, b []Float16) []Float16 {
// Currently just calls the regular slice operation
// Future versions may implement SIMD optimizations
return MulSlice(a, b)
}