Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-7 of 7 total  RSS 

Float to_s hack for easy sprintf'ing

Float Hacks:
1. to_s override.
I really hate using sprintf, mainly because i always have to go online
and look up the syntax. I figured i could make that a little easier.
Now you can print floats with different precision as easily as:

4.123456.to_s(1) # => "4.1"
4.123456.to_s(3) # => "4.12"
4.123456.to_s(3) # => "4.123"
4.123456.to_s(4) # => "4.1235" (Note the auto rounding from 4.123456)
4.123456.to_s # => "4.123456"


class Float
  alias_method :orig_to_s, :to_s
  def to_s(arg = nil)
    if arg.nil?
      orig_to_s
    else
      sprintf("%.#{arg}f", self)
    end
  end
end


I have packaged this and other useful hacks into a plugin at http://blog.djdossiers.com/articles/2007/03/31/new-rails-plugin-jakes-toolbox

Peace

--jake

Decimal to fraction in Ruby

// Adds a 'to_fraction' method to Float. Eg. 0.5.to_fraction => [1,2]

class Float
  def number_decimal_places
    self.to_s.length-2
  end
  
  def to_fraction
    higher = 10**self.number_decimal_places
    lower = self*higher

    gcden = greatest_common_divisor(higher, lower)

    return (lower/gcden).round, (higher/gcden).round
  end
  
private

  def greatest_common_divisor(a, b)
     while a%b != 0
       a,b = b.round,(a%b).round
     end 
     return b
  end
end

Java - Float Approximate

// Float approximate

float a = 10F;
float b = 3F;
float c = a/b;
	
NumberFormat nf = NumberFormat.getInstance();

System.out.println(nf.format(c));

Extend Float and FixNum to do calculations in S.I. units

Found at http://stephan.walter.name/Ruby_snippets

module SiUnits
        def mega;  self * 1000.kilo;   end
        def kilo;  self * 1000;        end
        def milli; self * 0.001;       end
        def micro; self * 0.001.milli; end

        def seconds; self;              end
        def minutes; self * 60;         end
        def hours;   self * 60.minutes; end
        def days;    self * 24.hours;   end
        def years;   self * 365.days;   end

        def metres; self; end

        def grams; self * 0.001; end
end

class Float; include SiUnits; end
class Fixnum; include SiUnits; end

p 2.days             # => 172800
p 3.milli.metres     # => 0.003
p 4.kilo.grams       # => 4.0


Note: This code is under the Creative Commons Attribution-NonCommercial-ShareAlike License.

BigNumber //JavaScript Class


Offers a extremely high precision level to make mathematical operations. For integers there is no limits and for floating point numbers, the class allows setting the maximum precision.

[UPDATED CODE AND HELP CAN BE FOUND HERE]

The class always returns new instances of BigNumber on the operations, so to the set value of a object, use the "set" method.


//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/classes/bignumber [v1.0]

BigNumber = function(n, p, r){
    var o = this, i;
    if(n instanceof BigNumber){
        for(i in {precision: 0, roundType: 0, _sign: 0, _dec: 0}) o[i] = n[i];
        o._buffer = n._buffer.slice();
        return;
    }
    o.precision = isNaN(p = Math.abs(p)) ? BigNumber.defaultPrecision : p;
    o.roundType = isNaN(r = Math.abs(r)) ? BigNumber.defaultRoundType : r;
    o._sign = (n += "").charAt(0) == "-";
    o._dec = ((n = n.replace(/[^\d.]/g, "").split(".", 2))[0] = n[0].replace(/^0+/, "") || "0").length;
    for(i = (n = o._buffer = (n.join("") || "0").split("")).length; i; n[--i] = +n[i]);
    o.round();
};
with({$: BigNumber, o: BigNumber.prototype}){
    $.ROUND_HALF_EVEN = ($.ROUND_HALF_DOWN = ($.ROUND_HALF_UP = ($.ROUND_FLOOR = ($.ROUND_CEIL = ($.ROUND_DOWN = ($.ROUND_UP = 0) + 1) + 1) + 1) + 1) + 1) + 1;
    $.defaultPrecision = 40;
    $.defaultRoundType = $.ROUND_HALF_UP;
    o.add = function(n){
        if(this._sign != (n = new BigNumber(n))._sign) return n._sign = !n._sign, this.subtract(n);
        var o = new BigNumber(this), a = o._buffer, b = n._buffer, la = o._dec,
        lb = n._dec, n = Math.max(la, lb), i, r;
        la != lb && ((lb = la - lb) > 0 ? o._zeroes(b, lb, 1) : o._zeroes(a, -lb, 1));
        i = (la = a.length) == (lb = b.length) ? a.length : ((lb = la - lb) > 0 ? o._zeroes(b, lb) : o._zeroes(a, -lb)).length;
        for(r = 0; i; r = (a[--i] = a[i] + b[i] + r) / 10 >>> 0, a[i] %= 10);
        return r && ++n && a.unshift(r), o._dec = n, o.round();
    };
    o.subtract = function(n){
        if(this._sign != (n = new BigNumber(n))._sign) return n._sign = !n._sign, this.add(n);
        var o = new BigNumber(this), x = o.compare(n) + 1, a = x ? o : n, b = x ? n : o, la = a._dec, lb = b._dec, n = la, i, j;
        a = a._buffer, b = b._buffer, la != lb && ((lb = la - lb) > 0 ? o._zeroes(b, lb, 1) : o._zeroes(a, -lb, 1));
        for(i = (la = a.length) == (lb = b.length) ? a.length : ((lb = la - lb) > 0 ? o._zeroes(b, lb) : o._zeroes(a, -lb)).length; i;){
            if(a[--i] < b[i]){
                for(j = i; j && !a[--j]; a[j] = 9);
                --a[j], a[i] += 10;
            }
            b[i] = a[i] - b[i];
        }
        return o._sign = !x, o._dec = n, o._buffer = b, o.round();
    };
    o.multiply = function(n){
        var o = new BigNumber(this), r = o.compare(n = new BigNumber(n)) + 1, a = (r ? o : n)._buffer,
        b = (r ? n : o)._buffer, la = a.length, lb = b.length, x = new BigNumber, i, j, s;
        for(i = lb; i; x.set(x.add(new BigNumber(s.join("")))))
            for(s = (new Array(lb - --i)).join("0").split(""), r = 0, j = la; j;
            r += a[--j] * b[i], s.unshift(r % 10), r = r / 10 >>> 0);
        return r && x._buffer.unshift(r), o._dec = (o._buffer = x._buffer).length - la - lb + o._dec + n._dec, o.round();
    };
    o.divide = function(n){
        if((n = new BigNumber(n)) == "0") throw new Error("division by 0");
        var o = new BigNumber(this), a = o._buffer, b = n._buffer, la = a.length - o._dec,
        lb = b.length - n._dec, s = a._sign != b._sign, dec = 0, buffer = [], x = new BigNumber, y, i;
        la != lb && ((lb = la - lb) > 0 ? o._zeroes(b, lb) : o._zeroes(a, -lb));
        o._dec = a.length, n._dec = b.length;
        b = n, a._sign = false, b._sign = false;
        while(o != 0 && (buffer.length - dec) <= o.precision){
            x.set(0);
            for(i = 0; o.compare(y = x.add(b)) + 1 && ++i; x.set(y));
            if(!i){
                do ++i, o._buffer.push(0), ++o._dec;
                while(o.compare(b) < 0);
                !dec && (!buffer.length && buffer.push(0), dec = buffer.length);
                o._zeroes(buffer, --i);
                continue;
            }
            o.set(o.subtract(x)), buffer.push(i);
        }
        return o._buffer = buffer, o._dec = dec ? dec : buffer.length, o.round();
    };
    o.mod = function(n){
        return this.subtract(this.divide(n).intPart().multiply(n));
    };
    o.pow = function(n){
        var o = new BigNumber(this), i;
        if(n == 0) return o.set(1);
        for(i = Math.abs(n); --i; o.set(o.multiply(this)));
        return n < 0 ? o.set((new BigNumber(1)).divide(o)) : o;
    };
    o.set = function(n){
        return this.constructor(n), this;
    };
    o.compare = function(n){
        var a = this, la = this._dec, b = n, lb = n._dec, i, l;
        if(la != lb) return la > lb ? 1 : -1;
        for(la = (a = a._buffer).length, lb = (b = b._buffer).length, i = -1, l = Math.min(la, lb); ++i < l;)
            if(a[i] != b[i]) return a[i] > b[i] ? 1 : -1;
        return la != lb ? la > lb ? 1 : -1 : 0;
    }
    o.negate = function(){
        var n = new BigNumber(this); return n._sign ^= 1, n;
    };
    o.abs = function(){
        var n = new BigNumber(this); return n._sign = 0, n;
    };
    o.intPart = function(){
        return new BigNumber((this._sign ? "-" : "") + (this._buffer.slice(0, this._dec).join("") || "0"));
    };
    o.valueOf = o.toString = function(){
        var o = this;
        return (o._sign ? "-" : "") + (o._buffer.slice(0, o._dec).join("") || "0") + (o._dec != o._buffer.length ? "." + o._buffer.slice(o._dec).join("") : "");
    };
    o._zeroes = function(n, l, t){
        var s = ["push", "unshift"][t || 0];
        for(++l; --l;  n[s](0));
        return n;
    };
    o.round = function(){
        if("_rounding" in this) return this;
        var $ = BigNumber, r = this.roundType, b = this._buffer, d, p, n, x;
        for(this._rounding = true; this._dec > 1 && !b[0]; --this._dec, b.shift());
        for(d = this._dec, p = this.precision + d, n = b[p]; b.length > d && !b[b.length -1]; b.pop());
        x = (this._sign ? "-" : "") + (p - d ? "0." + this._zeroes([], p - d - 1).join("") : "") + 1;
        if(b.length > p){
            n && (r == $.DOWN ? false : r == $.UP ? true : r == $.CEIL ? !this._sign
            : r == $.FLOOR ? this._sign : r == $.HALF_UP ? n >= 5 : r == $.HALF_DOWN ? n > 5
            : r == $.HALF_EVEN ? n >= 5 && b[p - 1] & 1 : false) && this.add(x);
            b.splice(p, b.length - p);
        }
        return delete this._rounding, this;
    };
}


Usage

<script type="text/javascript">

var x = new BigNumber("10"), y = new BigNumber("-2");
alert(x.pow(y));
alert(x.pow(1234));

alert((new BigNumber("99999999999999999999999999999999999")).add("999999999999999999999999999.99999999999999999"));

</script>

A range function with float increment

Taken from Edvard Majakari's comment in this recipe.

def arange(start, stop=None, step=None):
    if stop is None:
        stop = float(start)
        start = 0.0
    if step is None:
        step = 1.0
    cur = float(start)
    while cur < stop:
        yield cur
        cur += step

For python 2.2 (e.g. pys60) you need to do a "from __future__ import generators" first.
To get the list from the generator, use list(arange(...))

Binary Data Parser //Javascript Class



This is a prototyped class written to serialize and unserialize binary data, so you can read and write binary data files to exchange with programs written in languages like C and Pascal.

Currently the class is able to handle just the following types: signed integers (small 8 bits, short 16 bits, int 32 bits), unsigned integers (byte 8 bits, word 16 bits, dword 32 bits) and floating point (IEEE754 float 32 bits and double 64 bits).

The endianess of the binary values representation can also be configured with the class.

[UPDATED CODE AND HELP CAN BE FOUND HERE]


There's a php version right here.

Code

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/classes/binary-parser [v1.0]

BinaryParser = function( bigEndian, allowExceptions ){
	this.bigEndian = bigEndian;
	this.allowExceptions = allowExceptions;
};
with( { p: BinaryParser.prototype } ){
	with( {p: ( p.Buffer = function( bigEndian, buffer ){ this.bigEndian = bigEndian || 0; this.buffer = []; this.setBuffer( buffer ); } ).prototype } ){
		p.setBuffer = function( data ){
			if( data ){
				for( var l, i = l = data.length, b = this.buffer = new Array( l ); i; b[l - i] = data.charCodeAt( --i ) );
				this.bigEndian && b.reverse();
			}
		};
		p.hasNeededBits = function( neededBits ){
			return this.buffer.length >= -( -neededBits >> 3 );
		};
		p.checkBuffer = function( neededBits ){
			if( !this.hasNeededBits( neededBits ) )
				throw new Error( "checkBuffer::missing bytes" );
		};
		p.readBits = function( start, length ){
			//shl fix: Henri Torgemane ~1996 (compressed by Jonas Raoni)
			function shl( a, b ){
				for( ; b--; a = ( ( a %= 0x7fffffff + 1 ) & 0x40000000 ) == 0x40000000 ? a * 2 : ( a - 0x40000000 ) * 2 + 0x7fffffff + 1 );
				return a;
			}
			if( start < 0 || length <= 0 )
				return 0;
			this.checkBuffer( start + length );
			for( var offsetLeft, offsetRight = start % 8, curByte = this.buffer.length - ( start >> 3 ) - 1, lastByte = this.buffer.length + ( -( start + length ) >> 3 ), diff = curByte - lastByte, sum = ( ( this.buffer[ curByte ] >> offsetRight ) & ( ( 1 << ( diff ? 8 - offsetRight : length ) ) - 1 ) ) + ( diff && ( offsetLeft = ( start + length ) % 8 ) ? ( this.buffer[ lastByte++ ] & ( ( 1 << offsetLeft ) - 1 ) ) << ( diff-- << 3 ) - offsetRight : 0 ); diff; sum += shl( this.buffer[ lastByte++ ], ( diff-- << 3 ) - offsetRight ) );
			return sum;
		};
	}
	p.warn = function( msg ){
		if( this.allowExceptions )
			throw new Error( msg );
		return 1;
	};
	p.decodeFloat = function( data, precisionBits, exponentBits ){
		var b = new this.Buffer( this.bigEndian, data );
		b.checkBuffer( precisionBits + exponentBits + 1 );
		var bias = Math.pow( 2, exponentBits - 1 ) - 1, signal = b.readBits( precisionBits + exponentBits, 1 ), exponent = b.readBits( precisionBits, exponentBits ), significand = 0,
		divisor = 2, curByte = b.buffer.length + ( -precisionBits >> 3 ) - 1;
		do
			for( var byteValue = b.buffer[ ++curByte ], startBit = precisionBits % 8 || 8, mask = 1 << startBit; mask >>= 1; ( byteValue & mask ) && ( significand += 1 / divisor ), divisor *= 2 );
		while( precisionBits -= startBit );
		return exponent == ( bias << 1 ) + 1 ? significand ? NaN : signal ? -Infinity : +Infinity : ( 1 + signal * -2 ) * ( exponent || significand ? !exponent ? Math.pow( 2, -bias + 1 ) * significand : Math.pow( 2, exponent - bias ) * ( 1 + significand ) : 0 );
	};
	p.decodeInt = function( data, bits, signed ){
		var b = new this.Buffer( this.bigEndian, data ), x = b.readBits( 0, bits ), max = Math.pow( 2, bits );
		return signed && x >= max / 2 ? x - max : x;
	};
	p.encodeFloat = function( data, precisionBits, exponentBits ){
		var bias = Math.pow( 2, exponentBits - 1 ) - 1, minExp = -bias + 1, maxExp = bias, minUnnormExp = minExp - precisionBits,
		status = isNaN( n = parseFloat( data ) ) || n == -Infinity || n == +Infinity ? n : 0,
		exp = 0, len = 2 * bias + 1 + precisionBits + 3, bin = new Array( len ),
		signal = ( n = status !== 0 ? 0 : n ) < 0, n = Math.abs( n ), intPart = Math.floor( n ), floatPart = n - intPart,
		i, lastBit, rounded, j, result;
		for( i = len; i; bin[--i] = 0 );
		for( i = bias + 2; intPart && i; bin[--i] = intPart % 2, intPart = Math.floor( intPart / 2 ) );
		for( i = bias + 1; floatPart > 0 && i; ( bin[++i] = ( ( floatPart *= 2 ) >= 1 ) - 0 ) && --floatPart );
		for( i = -1; ++i < len && !bin[i]; );
		if( bin[( lastBit = precisionBits - 1 + ( i = ( exp = bias + 1 - i ) >= minExp && exp <= maxExp ? i + 1 : bias + 1 - ( exp = minExp - 1 ) ) ) + 1] ){
			if( !( rounded = bin[lastBit] ) )
				for( j = lastBit + 2; !rounded && j < len; rounded = bin[j++] );
			for( j = lastBit + 1; rounded && --j >= 0; ( bin[j] = !bin[j] - 0 ) && ( rounded = 0 ) );
		}
		for( i = i - 2 < 0 ? -1 : i - 3; ++i < len && !bin[i]; );
		if( ( exp = bias + 1 - i ) >= minExp && exp <= maxExp )
			++i;
		else if( exp < minExp ){
			exp != bias + 1 - len && exp < minUnnormExp && this.warn( "encodeFloat::float underflow" );
			i = bias + 1 - ( exp = minExp - 1 );
		}
		if( intPart || status !== 0 ){
			this.warn( intPart ? "encodeFloat::float overflow" : "encodeFloat::" + status );
			exp = maxExp + 1;
			i = bias + 2;
			if( status