Fixed is a Ruby gem that provides a fixed-point implementation of numbers with 18-digit precision. It is designed to avoid issues with floating-point rounding errors and ensures that arithmetic operations are performed with full precision. This gem is useful in situations where it is necessary to represent rational numbers with a high degree of precision, such as in scientific or financial applications.
Add this line to your application's Gemfile:
gem 'fixed'And then execute:
$ bundle install
Or install it yourself as:
$ gem install fixed
Here's an example of how to use the Fixed gem:
require 'fixed'
a = Fixed(5)
b = Fixed(3)
ratio = a / b
puts ratio.format(18) # => prints 1.666666666666666667In the above example, the Fixed gem allows you to perform arithmetic operations with high precision, avoiding rounding errors that can occur with floating-point numbers.
The Fixed class represents a fixed-point number with 18-digit precision.
Fixed.parse(str): Creates a newFixedinstance by parsing a string representation of a fixed-point number.Fixed.from_number(number): Creates a newFixedinstance from a numeric value.Fixed.from_fractions(fractions): Creates a newFixedinstance from the raw number of fractions.Fixed.smallest: Returns aFixedinstance representing the smallest possible value (1e-18).Fixed.zero: Returns aFixedinstance representing zero (0).
The Fixed class supports the following arithmetic operations:
+,-,*,/: Addition, subtraction, multiplication, and division operations.-@: Unary negation (returns a newFixedinstance with the opposite sign).abs: Returns the absolute value of theFixedinstance.
The Fixed class includes the Comparable module, allowing you to compare instances of Fixed using comparison operators such as <, >, <=, >=, ==, and <=>.
to_s(precision = 8): Returns a string representation of theFixedinstance with the specified precision.format(precision = 8): Returns a formatted string representation of theFixedinstance with the specified precision.pretty_format(precision = 8): Returns a formatted string representation of theFixedinstance with the specified precision, including thousands separators.
The Fixed gem also adds a Fixed method to the Kernel module, allowing you to create Fixed instances using a convenient syntax. For example:
a = Fixed(1)This is equivalent to:
a = Fixed.from_number(1)The Fixed gem extends the Numeric class with a to_fixed method, allowing you to convert numeric values to Fixed instances. For example:
number = 1.23
fixed = number.to_fixedBug reports and pull requests are welcome on GitHub at https://github.com/akuhn/fixed. This project encourages collaboration and appreciates contributions. Feel free to contribute to the project by reporting bugs or submitting pull requests.
The gem is available as open source under the terms of the MIT License.