From: Brian Candler Date: 2012-12-11T05:19:17+09:00 Subject: Re: Binary Fixed-Point in Ruby? (Improved FixedPt?) Axel Friedrich wrote in post #1088522: > FixedPt handels fixed-point binaries (not decimals). > > For example, this should work: > > fi = FixedPt.new(0.1,5,7) > > p fi.bin > gives: "11111" > but should give something like: "01100" What are the 5 and 7 meant to signify? 0.1 in decimal has no exact representation in binary. It would be 0.00011001100... I don't know of an existing library for working in fixed-point. If the number of digits after the binary point is fixed, then you could just work with integers with a power-of-two scaling factor - similar to working with cents instead of dollars. class FixBin def initialize(value, binbits) @value = (value * (1 << binbits)).to_i @binbits = binbits end def to_f @value * 1.0 / (1 << @binbits) end def to_s res = "%0#{@binbits+1}b" % @value res[-@binbits,0] = "." res end end a = FixBin.new(0.1, 7) puts a.to_f puts a.to_s -- Posted via http://www.ruby-forum.com/.