Author Topic: Exact Lua  (Read 3250 times)

0 Members and 1 Guest are viewing this topic.

Offline pianoman

  • LV6 Super Member (Next: 500)
  • ******
  • Posts: 426
  • Rating: +24/-0
  • ♪♫ ♪♫ ♪♫ ♪♫ ♪♫ ♪♫ ♪♫
    • View Profile
Exact Lua
« on: September 12, 2011, 06:26:28 pm »
I just realized that Lua doesn't give exact answers, only approximations.
Can you guys think of a way to get it to display exact answers?

Offline calc84maniac

  • eZ80 Guru
  • Coder Of Tomorrow
  • LV11 Super Veteran (Next: 3000)
  • ***********
  • Posts: 2912
  • Rating: +471/-17
    • View Profile
    • TI-Boy CE
Re: Exact Lua
« Reply #1 on: September 12, 2011, 07:01:34 pm »
Lua numbers are 64-bit floating point, they don't store any extra information like TI-Nspire Basic does about whether it's the square root of 3 or pi or whatever.
"Most people ask, 'What does a thing do?' Hackers ask, 'What can I make it do?'" - Pablos Holman

Offline NecroBumpist

  • LV4 Regular (Next: 200)
  • ****
  • Posts: 130
  • Rating: +14/-5
  • Master of Lua
    • View Profile
Re: Exact Lua
« Reply #2 on: September 12, 2011, 07:36:10 pm »
If you need more accuracy than Doubles can offer, you're going to have to create your own layer of abstraction.
This might be something like a Big Number library, or a complex number library.
Developing Lua scripts for the NSpire ?
Check out the Necrotorium
Need a few routines to run faster ? Checkout the MODS Lua Assembly Toolkit.
Need to save space for your scripts ? Checkout LuaSrcDiet

Offline Jim Bauwens

  • Lua! Nspire! Linux!
  • Editor
  • LV10 31337 u53r (Next: 2000)
  • **********
  • Posts: 1881
  • Rating: +206/-7
  • Linux!
    • View Profile
    • nothing...
Re: Exact Lua
« Reply #3 on: September 13, 2011, 03:54:00 am »
I would suggest to use math.eval and call basic function to do the calculation. But sadly enough getNum and getDenom don't work good through math.eval.
But ... gcd() (greatest common divisor) does, so I made my own function:
Code: (Lua) [Select]
function exact(n)
local n_int, n_float = math.modf(n)

local n_size = math.pow(10, #tostring(n_float)-2)

local num = n_float * n_size
local denom = n_size

local gcd = math.eval("gcd(" .. num .. "," .. denom .. ")")

num = num/gcd
denom = denom/gcd

return n_int, num, denom
end

It works like this:
Code: [Select]
big, num, denom = exact(13.125)big will be 13
num will be 1
denom will be 8
So, 13 1/8 .

It doesn't do any error checking though, thats your task :p
« Last Edit: September 13, 2011, 03:59:35 am by jimbauwens »

Offline pianoman

  • LV6 Super Member (Next: 500)
  • ******
  • Posts: 426
  • Rating: +24/-0
  • ♪♫ ♪♫ ♪♫ ♪♫ ♪♫ ♪♫ ♪♫
    • View Profile
Re: Exact Lua
« Reply #4 on: September 13, 2011, 11:04:36 pm »
Very interesting... thanks guys :)