[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
**Subject**: **Re: Numeric types, overhead and precision loss**
**From**: Ralph Hempel <rhempel@...>
**Date**: Fri, 18 May 2007 09:30:18 -0400

Luís Santos wrote:

Hello, people

`I am facing some problems with the default numeric type of the lua and
``that brought back to me an old question: why only one numeric type?
`

`If it is a floating point and you use it for integer calculations, can't
``you get unnecessary overhead? (nevermind the risk of precision loss)
`

`Is there any severe concerns about adding support for integer
``operations? Is it intended to be done using the userdata structure?
`

I am working on this problem in pbLua - a Lua 5.1 for the LEGO
Mindstorms NXT - and it's a big part of my Lua Gem.
I use long as the default numeric type to help with compatibility
in the calls between Lua and the driver code in the NXT. I felt
that the ARM7 (no FPP) would be crippled by having to do all the
math using doubles.
On top of that, I would be forever running out of precision when
I needed full 32 bit integers if I only used floats.
Basically, what I came up with was the concept of a "flong" data type
that is represented as a C union of long and float. The float type
fits into 32 bits.
So, for most of the things that the LEGO robots need to do, we use
the standard Lua numeric type, which is long. I wrote a custom
number parser that reads integers or floats. If the number has
a decimal point or exponent, it is stored as a float, otherwise
it's a long.
The disadvantage of this scheme is that you need to code special
routines for float math. The builtin +, -, etc only work on the
long data type.
So I added fadd(a,b) fsub(a,b) etc to work with floating point
numbers (that were actually longs). I also picked up a nice
little floating point math library from the net and linked that
in to do trig, logs, sqrt, etc.
It's a compromise, but that's what the whole world of computer
science comes down to.
Ralph