Namespaces
Variants
Actions

Fixed-point math for Python

Jump to: navigation, search
Article Metadata

Tested with
Devices(s): Nokia N95 8GB

Compatibility
Platform(s): S60 3rd Edition

Platform Security
Capabilities: )

Article
Keywords: math
Created: lpvalente (03 Dec 2009)
Last edited: hamishwillee (08 May 2013)

Introduction

Fixed-point math is a technique for representing floating point numbers as integers. By using this technique one is able to simulate floating point operations on hardware that don't support them (or at least on hardware that don't have dedicated floating point units, as many of current devices). This technique has been used used on many graphics applications (i.e. games).

The source code represents numbers with 32 bit integers, using 16 bits to represent the fractional part.

Source Code

import math
 
def degreeToRad (angle):
return math.radians(angle)
 
#
def radToDegree (angle):
return math.degrees(angle)
 
#
def int2fixed (value):
return value << 16
 
#
def float2fixed (value):
return int(value * 65536.0)
 
#
def fixed2int (value):
return value >> 16
 
#
def fixed2float (value):
return value * 0.0000152587890625 # (1/65536.0)
 
# should be 64-bit math
def fixed_mul (op1, op2):
r = long(op1) * long(op2)
return r >> 16
 
# should be 64-bit math
def fixed_div (op1, op2):
o1 = long (op1) << 16
r = long (o1 / long (op2) )
return int(r)
 
# some fixed point constants
PIx = float2fixed (pi)
 
# one
ONEx = int2fixed (1)
 
# zero
ZEROx = 0
This page was last modified on 8 May 2013, at 07:28.
127 page views in the last 30 days.
Nokia Developer aims to help you create apps and publish them so you can connect with users around the world.

京ICP备05048969号  © Copyright Nokia 2013 All rights reserved