Property definitions

gmp $ Ratio :: defaultinit
# Multi precision Rational numbers.
#
#     assert((0.2 + 0.1) == 0.30000000000000004)
#     assert(("1/5".to_r + "1/10".to_r) == "3/10".to_r)
class Ratio
    super Numeric
    super FinalizableOnce

    redef type OTHER: Ratio

    private var val: NativeMPQ

    redef fun hash do return self.to_i

    redef fun <=>(r) do
        var res = val.cmp(r.val)
        if (res) < 0 then
            return -1
        else if (res) > 0 then
            return 1
        else
            return 0
        end
    end

    redef fun ==(r) do return r isa Ratio and (self <=> r) == 0
    redef fun <=(r) do return (self <=> r) <= 0
    redef fun <(r) do return (self <=> r) < 0
    redef fun >=(r) do return (self <=> r) >= 0
    redef fun >(r) do return (self <=> r) > 0

    #     assert("3/2".to_r + "5/2".to_r == 4.to_r)
    redef fun +(r) do
        var res = new NativeMPQ
        val.add(res, r.val)
        return new Ratio(res)
    end

    #     assert( -("1/2".to_r) == ("-1/2").to_r)
    redef fun - do
        var res = new NativeMPQ
        val.neg res
        return new Ratio(res)
    end

    #     assert("5/2".to_r - "3/2".to_r == 1.to_r)
    redef fun -(r) do
        var res = new NativeMPQ
        val.sub(res, r.val)
        return new Ratio(res)
    end

    #     assert("3/2".to_r * 2.to_r == 3.to_r)
    redef fun *(r) do
        var res = new NativeMPQ
        val.mul(res, r.val)
        return new Ratio(res)
    end

    #     assert(3.to_r / 2.to_r == "3/2".to_r)
    redef fun /(r) do
        var res = new NativeMPQ
        val.div(res, r.val)
        return new Ratio(res)
    end

    # The absolute value of `self`.
    #
    #     assert((-3.to_r).abs == 3.to_r)
    #     assert(3.to_r.abs == 3.to_r)
    fun abs: Ratio do
        var res = new NativeMPQ
        val.abs res
        return new Ratio(res)
    end

    #     assert((3.to_r).zero == 0.to_r)
    redef fun zero do return new Ratio(new NativeMPQ)

    #     assert((3.to_r).value_of(2) == 2.to_r)
    redef fun value_of(n) do return n.to_r

    #     assert("7/2".to_r.to_i == 3)
    redef fun to_i do
        var res = new NativeMPZ
        val.numref.tdiv_q(res, val.denref)
        return res.get_si
    end

    #     assert(3.to_r.to_f == 3.0)
    redef fun to_f do return val.get_d

    #     assert(3.to_r.to_s == "3")
    redef fun to_s do
        var cstr = val.get_str(10i32)
        var str = cstr.to_s
        cstr.free
        return str
    end

    #     assert("7/2".to_r.to_bi == 3.to_bi)
    redef fun to_bi do
        var res = new NativeMPZ
        val.numref.tdiv_q(res, val.denref)
        return new BigInt(res)
    end

    redef fun to_r do return self

    redef fun finalize_once do val.finalize
end
lib/gmp/gmp.nit:289,1--399,3