Skip to content

Instantly share code, notes, and snippets.

@christianpeel
Last active Aug 29, 2015
Embed
What would you like to do?
FixedPoint
import Base: show, convert
FPEXP = 2
fpexp() = FPEXP;
function fpexp(n::Integer)
global FPEXP = n
end
immutable FixedP <: Real
num::Integer
FixedP(x::Integer) = new(x<<FPEXP);
FixedP(x::FloatingPoint) = new(convert(Integer,x*2.0^FPEXP));
end
convert(::Type{FloatingPoint}, x::FixedP) = FloatingPoint(x.num)/2.0^FPEXP
Qnum(z::FixedP) = z.num
-(z::FixedP) = FixedP(-Qnum(z)>>FPEXP);
-(z::FixedP, w::FixedP) = FixedP(FloatingPoint(Qnum(z) - Qnum(w))/2.0^FPEXP)
+(z::FixedP, w::FixedP) = FixedP(FloatingPoint(Qnum(z) + Qnum(w))/2.0^FPEXP)
*(z::FixedP, w::FixedP) = FixedP(FloatingPoint(Qnum(z) * Qnum(w))/2.0^(2*FPEXP))
/(z::FixedP, w::FixedP) = FixedP(FloatingPoint(Qnum(z) / Qnum(w)))
function show(io::IO, x::FixedP)
show(io, FloatingPoint(Qnum(x))/2.0^FPEXP)
end
import Base: show, convert
# FPEXP is the fixed point exponent, or the number of bits for values to the
# right of the binary point (decimal point). It's a global variable in this
# toy example.
FPEXP = 2
fpexp() = FPEXP;
function fpexp(n::Integer)
global FPEXP = n
end
# The core type, with constructor
immutable FixedP{T<:Integer} <: Real
num::T
FixedP(num::T, den::FloatingPoint) = new(convert(T,den*2.0^FPEXP))
end
FixedP{T<:Integer}(n::T, d::FloatingPoint) = FixedP{T}(n,d)
FixedP(n::Integer, d::FloatingPoint) = FixedP(promote(n,d)...)
FixedP(n::Integer) = FixedP(n,FloatingPoint(1))
FixedP(d::FloatingPoint) = FixedP(Int64(1),d)
convert(::Type{FloatingPoint}, x::FixedP) = FloatingPoint(x.num)/2.0^FPEXP
convert(::Type{FixedP}, x::FixedP) = x
Qnum(z::FixedP) = z.num
-(z::FixedP) = FixedP(typeof(Qnum(z)),-Qnum(z)>>FPEXP);
-(z::FixedP, w::FixedP) = FixedP(FloatingPoint(Qnum(z) - Qnum(w))/2.0^FPEXP)
+(z::FixedP, w::FixedP) = FixedP(FloatingPoint(Qnum(z) + Qnum(w))/2.0^FPEXP)
*(z::FixedP, w::FixedP) = FixedP(FloatingPoint(Qnum(z) * Qnum(w))/2.0^(2*FPEXP))
/(z::FixedP, w::FixedP) = FixedP(FloatingPoint(Qnum(z) / Qnum(w)))
function show(io::IO, x::FixedP)
show(io, FloatingPoint(Qnum(x))/2.0^FPEXP)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment