Package gocalc is for evaluating mathematical expressions at runtime. See https://github.com/justinsacbibit/gocalc-cl-sample for a sample console app that uses gocalc.
Package set represents the mathematical set.
Package meval provides a mathematical expresison parser. It can parse mathematical expresison into an AST and evaluate it. It also support the concept of variable through Context : An Expression can refer any other expression defined in a Context. For simple case use, a nil Context could be used (any expression refering another expression will fail at evaluation). An expression can be parsed using Compile, and evaluated with a nil context. See #Expression basic example. One can use context, in order for your expression to refer to others, aka variable. TODO(tuleu): document a context and how to use it TODO(tuleu) package global example
Package units provides type Bytes, which implements fmt.Formatter and can be easily formatted to various human-readable string using std fmt package. It also has some mathematics methods to modify the value. See example_test.go. The formatting result typically consists of a number and a unit. There are binary units (kiB, MiB, GiB and TiB), decimal units (kB, MB, GB and TB) and base unit B. Further reading: https://en.wikipedia.org/wiki/Binary_prefix. When calculating the output number, binary units are used by default. You can switch to decimal units by adding the '#' flag. Why is there no 'PiB/PB'? 'TiB/TB' is sufficient for most cases, and many non-technical people are not familiar with 'PiB/PB'. Examples: Examples: Sign for numbers ('+'), left-justify ('-') and zero padding ('0') are not supported. The width includes the unit.
Package galoisfield implements the `GF(2**m)` Galois finite fields. What is a Galois field? A Galois field, also known as a finite field, is a mathematical field with a number of elements equal to a prime number to a positive integer power. While finite fields with a prime number of elements are familiar to most programmers -- boolean arithmetic, a.k.a. arithmetic `mod 2` is a well-known example -- fields that take that prime to powers higher than 1 is less well-known. Basically, an element of `GF(2**m)` can be seen as a list of `m` bits, where addition and multiplication are elementwise `mod 2` (`a XOR b` for addition, `a AND b` for multiplication) and the remaining rules of field arithmetic follow from linear algebra (vectors, or alternatively, polynomial coefficients). Short version: an element of `GF(2**8)` element may be represented as a byte (0 ≤ n ≤ 255), but it's really a vector of 8 bits -- like a very primitive MMX/SSE. We then treat said vector as the coefficients of a polynomial, and that allows us to define multiplication, giving us a full mathematical field. Finite fields -- and `GF(2**8)` in particular -- get a tons of use in codes, in both the "error-correcting code" and "cryptographic code" senses. However, this implementation has NOT been hardened against timing attacks, so it MUST NOT be used in cryptography.
Package libquickjs is a CGo-free, ccgo/v4 version of libquickjs.a, a library implementing an embeddable Javascript engine. It supports the ES2023 specification including modules, asynchronous generators, proxies and BigInt. It optionally supports mathematical extensions such as big decimal floating point numbers (BigDecimal), big binary floating point numbers (BigFloat) and operator overloading. These combinations of GOOS and GOARCH are currently supported Builder results available at: https://modern-c.appspot.com/-/builder/?importpath=modernc.org%2flibquickjs If a builder reports PASS then this package passed all the test262 suite test cases the original C version passed on the respective target.
Package record provides a thin wrapper over a native composite map data structure that simplifies access to the final (leaf) values. Some database SDKs return such composite map structures when fetching a record. - We assume all keys are strings in order to simplify access. - Record values are accessed/set by providing a string representation of the path separated by ".". For example, passing "key1.key2" to a Record fetchs the value with key "key2" in the subrecord S of the record R, where the key of S is "key1". Mathematically, we can view a composite map as a function f whose domain is the subset X of finite length tuples of the countable product of some key set A. For each index i, fi is a function from A to the set of possible values. Then f(k1, k2, k3, ..., kn) := f1 (f2 ... fn(kn)). This makes the dot notation for paths quite natural.
Package math32 provides basic constants and mathematical functions for float32 types. At its core, it's mostly just a wrapper in form of float32(math.XXX). This applies to the following functions: Everything else is a float32 implementation. Implementation schedule is sporadic an uncertain. But eventually all functions will be replaced
Package decimal implements immutable decimal floating-point numbers. It is specifically designed for transactional financial systems and adheres to the principles set by ANSI X3.274-1996. Decimal is a struct with three fields: The numerical value of a decimal is calculated as follows: This approach allows the same numeric value to have multiple representations, for example, 1, 1.0, and 1.00, which represent the same value but have different scales and coefficients. The range of a decimal is determined by its scale. Here are the ranges for frequently used scales: Subnormal numbers are not supported to ensure peak performance. Consequently, decimals between -0.00000000000000000005 and 0.00000000000000000005 inclusive, are rounded to 0. Special values such as NaN, Infinity, or negative zeros are not supported. This ensures that arithmetic operations always produce either valid decimals or errors. Each arithmetic operation occurs in two steps: The operation is initially performed using uint64 arithmetic. If no overflow occurs, the exact result is immediately returned. If overflow occurs, the operation proceeds to step 2. The operation is repeated with at least double precision using big.Int arithmetic. The result is then rounded to 19 digits. If no significant digits are lost during rounding, the inexact result is returned. If any significant digit is lost, an overflow error is returned. Step 1 improves performance by avoiding the performance impact associated with big.Int arithmetic. It is expected that, in transactional financial systems, most arithmetic operations will compute an exact result during step 1. The following rules determine the significance of digits during step 2: All transcendental functions are always computed with at least double precision using big.Int arithmetic. The result is then rounded to 19 digits. If no significant digits are lost during rounding, the inexact result is returned. If any significant digit is lost, an overflow error is returned. The following rules determine the significance of digits: Unlike many other decimal libraries, this package does not provide an explicit mathematical context. Instead, the context is implicit and can be approximately equated to the following settings: The equality of Etiny and Emin implies that this package does not support subnormal numbers. For all operations, the result is the one that would be obtained by computing the exact result with infinite precision and then rounding it to 19 digits using half-to-even rounding. This method ensures that the result is as close as possible to the true mathematical value and that rounding errors are evenly distributed between rounding up and down. In addition to implicit rounding, the package provides several methods for explicit rounding: See the documentation for each method for more details. All methods are panic-free and pure. Errors are returned in the following cases: Division by Zero: Unlike Go's standard library, Decimal.Quo, Decimal.QuoRem, Decimal.Inv, Decimal.AddQuo, Decimal.SubQuo, do not panic when dividing by 0. Instead, they return an error. Invalid Operation: Sum, Mean and Prod return an error if no arguments are provided. Decimal.PowInt returns an error if 0 is raised to a negative power. Decimal.Sqrt returns an error if the square root of a negative decimal is requested. Decimal.Log, Decimal.Log2, Decimal.Log10 return an error when calculating the natural logarithm of a non-positive decimal. Decimal.Pow returns an error if 0 is raised to a negative powere or a negative decimal is raised to a fractional power. Overflow: Unlike standard integers, decimals do not "wrap around" when exceeding their maximum value. For out-of-range values, methods return an error. Errors are not returned in the following cases: A. JSON The package integrates seamlessly with standard encoding/json through the implementation of encoding.TextMarshaller and encoding.TextUnmarshaler interfaces. Below is an example structure: This package marshals decimals as quoted strings, ensuring the preservation of the exact numerical value. Below is an example OpenAPI schema: B. XML The package integrates with standard encoding/xml via the implementation of encoding.TextMarshaller and encoding.TextUnmarshaler interfaces. Below is an example structure: "xs:decimal" type can represent decimals in XML schema. It is possible to impose restrictions on the length of the decimals using the following type: C. Protocol Buffers Protocol Buffers provide two formats to represent decimals. The first format represents decimals as numerical strings. The main advantage of this format is that it preserves trailing zeros. To convert between this format and decimals, use Parse and Decimal.String. Below is an example of a proto definition: The second format represents decimals as a pair of integers: one for the integer part and another for the fractional part. This format does not preserve trailing zeros and rounds decimals with more than nine digits in the fractional part. For conversion between this format and decimals, use NewFromInt64 and Decimal.Int64 with a scale argument of "9". Below is an example of a proto definition: D. SQL The package integrates with the standard database/sql via the implementation of sql.Scanner and driver.Valuer interfaces. To ensure accurate preservation of decimal scales, it is essential to choose appropriate column types: Below are the reasons for these preferences: PostgreSQL: Always use DECIMAL without precision or scale specifications, that is, avoid DECIMAL(p) or DECIMAL(p, s). DECIMAL accurately preserves the scale of decimals. SQLite: Prefer TEXT, since DECIMAL is just an alias for binary floating-point numbers. TEXT accurately preserves the scale of decimals. MySQL: Use DECIMAL(19, d), as DECIMAL is merely an alias for DECIMAL(10, 0). The downside of this format is that MySQL automatically rescales all decimals: it rounds values with more than d digits in the fractional part (using half away from zero) and pads with trailing zeros those with fewer than d digits in the fractional part. To prevent automatic rescaling, consider using VARCHAR(22), which accurately preserves the scale of decimals. This example demonstrates the advantage of decimals for financial calculations. It computes the sum 0.1 + 0.2 using both decimal and float64 arithmetic. In decimal arithmetic, the result is exactly 0.3, as expected. In float64 arithmetic, the result is 0.30000000000000004 due to floating-point inaccuracy. This example calculates an approximate value of π using the Leibniz formula. The Leibniz formula is an infinite series that converges to π/4, and is given by the equation: 1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 + ... = π/4. This example computes the series up to the 500,000th term using decimal arithmetic and returns the approximate value of π. This example implements a simple calculator that evaluates mathematical expressions written in postfix notation. The calculator can handle basic arithmetic operations such as addition, subtraction, multiplication, and division.
Package GLaM provides mathematical types and operations for use with OpenGL.
Package expr provides a framework for parsing and evaluating mathematical expressions.
Package squaket implements the squaket data type. A squaket is simply a collection of composite data you could group based on a specific property. Take for example: The data you see are composite data having three properties, namely: name, age, and location. If we are to group them based on the similarity of their locations, we could have the following groups: This kind of collection of data is what we mean by squaket. In practice, elements of a squaket are expected to be structs. However, the elements of a squaket could have different properties, as long as they all have the grouping property. Real world example: Things to note: Why's the meaning of squaket? Well, we needed a name to describe a collection of things capable of being grouped, and we thought of "square brackets". As we know, square brackets are used to group things, in languages, mathematics, and programming. So we shortened it, ending up with "squaket".
Mathematical art based on: https://blogs.scientificamerican.com/guest-blog/making-mathematical-art/
Package pbc provides structures for building pairing-based cryptosystems. It is a wrapper around the Pairing-Based Cryptography (PBC) Library authored by Ben Lynn (https://crypto.stanford.edu/pbc/). This wrapper provides access to all PBC functions. It supports generation of various types of elliptic curves and pairings, element initialization, I/O, and arithmetic. These features can be used to quickly build pairing-based or conventional cryptosystems. The PBC library is designed to be extremely fast. Internally, it uses GMP for arbitrary-precision arithmetic. It also includes a wide variety of optimizations that make pairing-based cryptography highly efficient. To improve performance, PBC does not perform type checking to ensure that operations actually make sense. The Go wrapper provides the ability to add compatibility checks to most operations, or to use unchecked elements to maximize performance. Since this library provides low-level access to pairing primitives, it is very easy to accidentally construct insecure systems. This library is intended to be used by cryptographers or to implement well-analyzed cryptosystems. Cryptographic pairings are defined over three mathematical groups: G1, G2, and GT, where each group is typically of the same order r. Additionally, a bilinear map e maps a pair of elements — one from G1 and another from G2 — to an element in GT. This map e has the following additional property: If G1 == G2, then a pairing is said to be symmetric. Otherwise, it is asymmetric. Pairings can be used to construct a variety of efficient cryptosystems. The PBC library currently supports 5 different types of pairings, each with configurable parameters. These types are designated alphabetically, roughly in chronological order of introduction. Type A, D, E, F, and G pairings are implemented in the library. Each type has different time and space requirements. For more information about the types, see the documentation for the corresponding generator calls, or the PBC manual page at https://crypto.stanford.edu/pbc/manual/ch05s01.html. This package must be compiled using cgo. It also requires the installation of GMP and PBC. During the build process, this package will attempt to include <gmp.h> and <pbc/pbc.h>, and then dynamically link to GMP and PBC. Most systems include a package for GMP. To install GMP in Debian / Ubuntu: For an RPM installation with YUM: For installation with Fink (http://www.finkproject.org/) on Mac OS X: For more information or to compile from source, visit https://gmplib.org/ To install the PBC library, download the appropriate files for your system from https://crypto.stanford.edu/pbc/download.html. PBC has three dependencies: the gcc compiler, flex (http://flex.sourceforge.net/), and bison (https://www.gnu.org/software/bison/). See the respective sites for installation instructions. Most distributions include packages for these libraries. For example, in Debian / Ubuntu: The PBC source can be compiled and installed using the usual GNU Build System: After installing, you may need to rebuild the search path for libraries: It is possible to install the package on Windows through the use of MinGW and MSYS. MSYS is required for installing PBC, while GMP can be installed through a package. Based on your MinGW installation, you may need to add "-I/usr/local/include" to CPPFLAGS and "-L/usr/local/lib" to LDFLAGS when building PBC. Likewise, you may need to add these options to CGO_CPPFLAGS and CGO_LDFLAGS when installing this package. This package is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. For additional details, see the COPYING and COPYING.LESSER files. This example generates a pairing and some random group elements, then applies the pairing operation. This example computes and verifies a Boneh-Lynn-Shacham signature in a simulated conversation between Alice and Bob.
Package geo contains a collection of 2-D types and other mathematical functions geared towards games. Includes This package assumes coordinates where +x is right and +y is down.
Package vision is a repository containing visual processing packages in Go (golang), focused mainly on providing efficient V1 (primary visual cortex) level filtering of images, with the output then suitable as input for neural networks. Two main types of filters are supported: * **Gabor** filters simulate V1 simple-cell responses in terms of an oriented sine wave times a gaussian envelope that localizes the filter in space. This produces an edge detector that detects oriented contrast transitions between light and dark. In general, the main principle of primary visual filtering is to focus on spatial (and temporal) changes, while filtering out static, uniform areas. * **DoG** (difference of gaussian) filters simulate retinal On-center vs. Off-center contrast coding cells -- unlike gabor filters, these do not have orientation tuning. Mathematically, they are a difference between a narrow (center) vs wide (surround) gaussian, of opposite signs, balanced so that a uniform input generates offsetting values that sum to zero. In the visual system, orientation tuning is constructed from aligned DoG-like inputs, but it is more efficient to just use the Gabor filters directly. However, DoG filters capture the "blob" cells that encode color contrasts. The `vfilter` package contains general-purpose filtering code that applies (convolves) any given filter with a visual input. It also supports converting an `image.Image` into a `tensor.Float32` tensor which is the main data type used in this framework. It also supports max-pooling for efficiently reducing the dimensionality of inputs. The `kwta` package provides an implementation of the feedforward and feedback (FFFB) inhibition dynamics (and noisy X-over-X-plus-1 activation function) from the `Leabra` algorithm to produce a k-Winners-Take-All processing of visual filter outputs -- this increases the contrast and simplifies the representations, and is a good model of the dynamics in primary visual cortex.
Package gomath contains an advanced mathematics library for the Go programming language. Check the sprec and dprec sub-packages for functions and types in the single and double floating point precision levels respectively.
Package spatial provides 2D positioning and movement infrastructure for entity placement and spatial queries without imposing game-specific rules. Purpose: This package handles all spatial mathematics, collision detection, and movement validation without imposing any game-specific movement rules or combat mechanics. It provides the mathematical foundation for position-based game systems. Scope: Non-Goals: Integration: This package integrates with: The spatial package is the foundation for any position-based mechanics but deliberately avoids encoding any game rules about how space is used. Example: Package spatial provides 2D spatial positioning and movement capabilities for RPG games. Package spatial provides 2D spatial positioning and movement capabilities for RPG games.
Package math provides basic constants and mathematical functions.
Package mym -- provides miscellaneous mathematical functions.
Package gomathx provides high-performance mathematical operations for Go. GoMathX is a comprehensive mathematical library featuring generic vectors, matrices, and linear algebra operations. It's designed for scientific computing, data analysis, and machine learning applications.
Copyright (c) 2023 thorstenrie All rights reserved. Use is governed with GNU Affero General Public License v3.0 that can be found in the LICENSE file. Copyright (c) 2023 thorstenrie All rights reserved. Use is governed with GNU Affero General Public License v3.0 that can be found in the LICENSE file. Copyright (c) 2023 thorstenrie All rights reserved. Use is governed with GNU Affero General Public License v3.0 that can be found in the LICENSE file. Copyright (c) 2023 thorstenrie All rights reserved. Use is governed with GNU Affero General Public License v3.0 that can be found in the LICENSE file. Copyright (c) 2023 thorstenrie All rights reserved. Use is governed with GNU Affero General Public License v3.0 that can be found in the LICENSE file. Copyright (c) 2023 thorstenrie All rights reserved. Use is governed with GNU Affero General Public License v3.0 that can be found in the LICENSE file. Copyright (c) 2023 thorstenrie All rights reserved. Use is governed with GNU Affero General Public License v3.0 that can be found in the LICENSE file. Package lpstats provides an interface for simple statistics in Go. The interface contains mathematical and statistical functions - Absolute value - Arithmetic mean of a discrete value array - Equal for slices of signed integers - Expected value for a uniform distribution - Near equal (for float types) - Sign - Square - Sum - Variance of a discrete value array - Variance of a uniform distribution Most functions take integer and float values as arguments. Copyright (c) 2023 thorstenrie All rights reserved. Use is governed with GNU Affero General Public License v3.0 that can be found in the LICENSE file. Copyright (c) 2023 thorstenrie All rights reserved. Use is governed with GNU Affero General Public License v3.0 that can be found in the LICENSE file. Copyright (c) 2023 thorstenrie All rights reserved. Use is governed with GNU Affero General Public License v3.0 that can be found in the LICENSE file.
Package decimal provides a high-performance, arbitrary precision, floating-point decimal library. This package provides floating-point decimal numbers, useful for financial programming or calculations where a larger, more accurate representation of a number is required. In addition to basic arithmetic operations (addition, subtraction, multiplication, and division) this package offers various mathematical functions, including the exponential function, various logarithms, and the ability to compute continued fractions. While lean, this package is full of features. It implements interfaces like “fmt.Formatter” and intuitively utilizes verbs and flags as described in the “fmt” package. (Also included: “fmt.Scanner”, “fmt.Stringer”, “encoding.TextUnmarshaler”, and “encoding.TextMarshaler”.) It allows users to specific explicit contexts for arithmetic operations, but doesn't require it. It provides access to NaN payloads and is more lenient when parsing a decimal from a string than the GDA specification requires. API interfaces have been changed slightly to work more seamlessly with existing Go programs. For example, many “Quantize” implementations require a decimal as both the receiver and argument which isn't very user friendly. Instead, this library accepts a simple “int” which can be derived from an existing decimal if required. It contains two modes of operation designed to make transitioning to various GDA "quirks" (like always rounding lossless operations) easier. There are three primary goals of this library: By adhering to the General Decimal Arithmetic specification, this package has a well-defined structure for its arithmetic operations. Decimal libraries are inherently slow; this library works diligently to minimize memory allocations and utilize efficient algorithms. Performance regularly benchmarks as fast or faster than many other popular decimal libraries. Libraries should be intuitive and work out of the box without having to configure too many settings; however, precise settings should still be available. The following type is supported: The zero value for a Big corresponds with 0, meaning all the following are valid: Method naming is the same as math/big's, meaning: In general, its conventions mirror math/big's. It is suggested to read the math/big package comments to gain an understanding of this package's conventions. Arguments to Binary and Unary methods are allowed to alias, so the following is valid: Unless otherwise specified, the only argument that will be modified is the result (“z”). This means the following is valid and race-free: But this is not:
Package gorgonia is a library that helps facilitate machine learning in Go. Write and evaluate mathematical equations involving multidimensional arrays easily. Do differentiation with them just as easily. Autodiff showcases automatic differentiation Basic example of representing mathematical equations as graphs. In this example, we want to represent the following equation Gorgonia provides an API that is fairly idiomatic - most of the functions in in the API return (T, error). This is useful for many cases, such as an interactive shell for deep learning. However, it must also be acknowledged that this makes composing functions together a bit cumbersome. To that end, Gorgonia provides two alternative methods. First, the `Lift` based functions; Second the `Must` function Linear Regression Example The formula for a straight line is We want to find an `m` and a `c` that fits the equation well. We'll do it in both float32 and float64 to showcase the extensibility of Gorgonia This example showcases the reasons for the more confusing functions. This example showcases dealing with errors. This is part 2 of the raison d'être of the more complicated functions - dealing with errors SymbolicDiff showcases symbolic differentiation
Package gochart makes numerical charts of mathematical functions.
Package eval provides mathematical expression evaluation.
Package stackage implements a flexible stack type optimized for use in creating and presenting conditional Boolean statements, abstract mathematical constructs, or simple lists: the possibilities are endless!
Package GLaM provides mathematical types and operations for use with OpenGL.
Package pbc provides structures for building pairing-based cryptosystems. It is a wrapper around the Pairing-Based Cryptography (PBC) Library authored by Ben Lynn (https://crypto.stanford.edu/pbc/). This wrapper provides access to all PBC functions. It supports generation of various types of elliptic curves and pairings, element initialization, I/O, and arithmetic. These features can be used to quickly build pairing-based or conventional cryptosystems. The PBC library is designed to be extremely fast. Internally, it uses GMP for arbitrary-precision arithmetic. It also includes a wide variety of optimizations that make pairing-based cryptography highly efficient. To improve performance, PBC does not perform type checking to ensure that operations actually make sense. The Go wrapper provides the ability to add compatibility checks to most operations, or to use unchecked elements to maximize performance. Since this library provides low-level access to pairing primitives, it is very easy to accidentally construct insecure systems. This library is intended to be used by cryptographers or to implement well-analyzed cryptosystems. Cryptographic pairings are defined over three mathematical groups: G1, G2, and GT, where each group is typically of the same order r. Additionally, a bilinear map e maps a pair of elements — one from G1 and another from G2 — to an element in GT. This map e has the following additional property: If G1 == G2, then a pairing is said to be symmetric. Otherwise, it is asymmetric. Pairings can be used to construct a variety of efficient cryptosystems. The PBC library currently supports 5 different types of pairings, each with configurable parameters. These types are designated alphabetically, roughly in chronological order of introduction. Type A, D, E, F, and G pairings are implemented in the library. Each type has different time and space requirements. For more information about the types, see the documentation for the corresponding generator calls, or the PBC manual page at https://crypto.stanford.edu/pbc/manual/ch05s01.html. This package must be compiled using cgo. It also requires the installation of GMP and PBC. During the build process, this package will attempt to include <gmp.h> and <pbc/pbc.h>, and then dynamically link to GMP and PBC. Most systems include a package for GMP. To install GMP in Debian / Ubuntu: For an RPM installation with YUM: For installation with Fink (http://www.finkproject.org/) on Mac OS X: For more information or to compile from source, visit https://gmplib.org/ To install the PBC library, download the appropriate files for your system from https://crypto.stanford.edu/pbc/download.html. PBC has three dependencies: the gcc compiler, flex (http://flex.sourceforge.net/), and bison (https://www.gnu.org/software/bison/). See the respective sites for installation instructions. Most distributions include packages for these libraries. For example, in Debian / Ubuntu: The PBC source can be compiled and installed using the usual GNU Build System: After installing, you may need to rebuild the search path for libraries: It is possible to install the package on Windows through the use of MinGW and MSYS. MSYS is required for installing PBC, while GMP can be installed through a package. Based on your MinGW installation, you may need to add "-I/usr/local/include" to CPPFLAGS and "-L/usr/local/lib" to LDFLAGS when building PBC. Likewise, you may need to add these options to CGO_CPPFLAGS and CGO_LDFLAGS when installing this package. This package is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. For additional details, see the COPYING and COPYING.LESSER files. This example generates a pairing and some random group elements, then applies the pairing operation. This example computes and verifies a Boneh-Lynn-Shacham signature in a simulated conversation between Alice and Bob.
Package money implements immutable amounts and exchange rates. Currency is represented as an integer index into an in-memory array that stores properties defined by ISO 4217: The currently supported currencies use scales of 0, 2, or 3: Amount is a struct with two fields: ExchangeRate is a struct with three fields: The range of an amount is determined by the scale of its currency. Similarly, the range of an exchange rate is determined by the scale of its quote currency. Here are the ranges for scales 0, 2, and 3: Subnormal numbers are not supported by the underlying decimal.Decimal type. Consequently, amounts and exchange rates between -0.00000000000000000005 and 0.00000000000000000005 inclusive are rounded to 0. The package provides methods for converting: See the documentation for each method for more details. Each arithmetic operation is carried out in two steps: The operation is initially performed using uint64 arithmetic. If no overflow occurs, the exact result is immediately returned. If an overflow does occur, the operation proceeds to step 2. The operation is repeated with increased precision using big.Int arithmetic. The result is then rounded to 19 digits. If no significant digits are lost during rounding, the inexact result is returned. If any significant digit is lost, an overflow error is returned. Step 1 was introduced to improve performance by avoiding heap allocation for big.Int and the complexities associated with big.Int arithmetic. It is expected that, in transactional financial systems, the majority of arithmetic operations will successfully compute an exact result during step 1. The following rules are used to determine the significance of digits during step 2: Amount.Add, Amount.Sub, Amount.SubAbs, Amount.Mul, Amount.FMA, Amount.Quo, Amount.QuoRem, ExchangeRate.Conv, ExchangeRate.Mul, ExchangeRate.Inv: All digits in the integer part are significant. In the fractional part, digits are significant up to the scale of the currency. Amount.Rat: All digits in the integer part are significant, while digits in the fractional part are considered insignificant. Implicit rounding is applied when a result exceeds 19 digits. In such cases, the result is rounded to 19 digits using half-to-even rounding. This method ensures that rounding errors are evenly distributed between rounding up and rounding down. For all arithmetic operations, the result is the one that would be obtained by computing the exact mathematical result with infinite precision and then rounding it to 19 digits. In addition to implicit rounding, the package provides several methods for explicit rounding: See the documentation for each method for more details. All methods are panic-free and pure. Errors are returned in the following cases: Currency Mismatch. All arithmetic operations, except for Amount.Rat, return an error if the operands are denominated in different currencies. Division by Zero. Unlike the standard library, Amount.Quo, Amount.QuoRem, Amount.Rat, and ExchangeRate.Inv do not panic when dividing by 0. Instead, they return an error. Overflow. Unlike standard integers, there is no "wrap around" for amounts at certain sizes. Arithmetic operations return an error for out-of-range values. Underflow. All arithmetic operations, except for ExchangeRate.Inv and ExchangeRate.Mul, do not return an error in case of underflow. If the result is an amount between -0.00000000000000000005 and 0.00000000000000000005 inclusive, it is rounded to 0. ExchangeRate.Inv and ExchangeRate.Mul return an error in cases of underflow, as the result of these operations is an exchange rate, and exchange rates cannot be 0. This example calculates the effective interest rate for a 10% nominal interest rate compounded monthly on a USD 10,000 balance. In this example, a loan amortization table is generated for a loan with an initial amount of USD 12,000, an annual interest rate of 10%, and a repayment period of 1 year. In this example, we parse the string "840D000000001234", which represents -12.34 USD, according to the specification for "DE54, Additional Amounts" in ISO 8583. This is an example of how to a parse a monetary amount formatted as money.proto. This is an example of how to a parse a monetary amount formatted according to Stripe API specification. In this example, the sales tax amount is calculated for a product with a given price after tax, using a specified tax rate.
gen-mkl-wrapper generates wrappers for Math Kernel Library routines. Math Kernel Library by Intel is widely used library of common mathematical routines, which provides support for various BLAS and LAPACK routines and many many more. Due to its root in Fortran and C, many routines' names contain the type its operates on, for example, the Cholesky Decomposition is For C++ or rust, it may be desired to dispatch the method based on the type. This becomes extremely handy when implementing something based on MKL for both 32-bit and 64-bit float point number. For in C++, below is valid Similarly in rust, the below is valid This simply binary does just the above - provided with a list of routines names, it will generate the rust trait or C++ polymorphic functions to those routines.
Package leven shtein implements distance and similarity metrics for strings, based on the Levenshtein measure. The Levenshtein `Distance` between two strings is the minimum total cost of edits that would convert the first string into the second. The allowed edit operations are insertions, deletions, and substitutions, all at character (one UTF-8 code point) level. Each operation has a default cost of 1, but each can be assigned its own cost equal to or greater than 0. A `Distance` of 0 means the two strings are identical, and the higher the value the more different the strings. Since in practice we are interested in finding if the two strings are "close enough", it often does not make sense to continue the calculation once the result is mathematically guaranteed to exceed a desired threshold. Providing this value to the `Distance` function allows it to take a shortcut and return a lower bound instead of an exact cost when the threshold is exceeded. The `Similarity` function calculates the distance, then converts it into a normalized metric within the range 0..1, with 1 meaning the strings are identical, and 0 that they have nothing in common. A minimum similarity threshold can be provided to speed up the calculation of the metric for strings that are far too dissimilar for the purpose at hand. All values under this threshold are rounded down to 0. The `Match` function provides a similarity metric, with the same range and meaning as `Similarity`, but with a bonus for string pairs that share a common prefix and have a similarity above a "bonus threshold". It uses the same method as proposed by Winkler for the Jaro distance, and the reasoning behind it is that these string pairs are very likely spelling variations or errors, and they are more closely linked than the edit distance alone would suggest. The underlying `Calculate` function is also exported, to allow the building of other derivative metrics, if needed.