Search code examples
luaquadraticti-nspire

Inspired Lua Program is Different on Computer and Calculator


I am attempting to create a simple quadratic formula program for my TI-Nspire CX CAS. I seem to have everything correct, and it works on the computer: enter image description here

However, it doesn't work on the calculator. I get the second one correct, but the 1st is -4.44089...e-16. (doesn't say ..., just using it because I don't want to type out the whole thing)

The (simplified) code is as follows:

function quadraticA(f,s,t)
    return ((-1*s)+math.sqrt(s^2-4*f*t))/(2*f)
end
function quadraticB(f,s,t)
    return ((-1*s)-math.sqrt(s^2-4*f*t))/(2*f)
end
function on.paint(gc)
    formula:setExpression("0s: "..quadraticA(tonumber(a),tonumber(b),tonumber(c)))
    formulaB:setExpression(quadraticB(tonumber(a),tonumber(b),tonumber(c)))
end

Why do I get a different answer on the calculator then on the computer? How can I fix the issue?

Thanks in advance!


Solution

  • As Dimitry pointed out, I must write, essentially, a CAS engine. Here is a square root simplification in lua:

    function factors(a)
        factorsOfA={}
        counter = 0
        for i = 1, a do
            counter = counter + 1
            if modulo(a,i) == 0 then
                factorsOfA[counter]=i
            end
        end
        return factorsOfA
    end
    function simplifySqrt(radicand)
        radicandFactors = factors(radicand)
        outsideRadicand = 1
        for m,i in pairs(radicandFactors) do
            if math.floor(math.sqrt(i))^2 == i then
                outsideRadicand = outsideRadicand * math.floor(math.sqrt(i))
            end
        end
        insideRadicand = radicand/outsideRadicand^2
        return outsideRadicand.."sqrt("..insideRadicand..")"
    end
    

    I hope this helps!