sosauce / CuteCalc

CuteCalc is a simple,lightweight and open-source calculator app for Android.
GNU General Public License v3.0
98 stars 8 forks source link

Root of a negative number causes app crash #61

Closed Ransomware3301 closed 6 months ago

Ransomware3301 commented 6 months ago

Describe the bug Taking the square root of a negative number causes an app crash

To Reproduce Choose a negative number and take the square root of that

Expected behavior Print "Error" instead of causing an app crash

Smartphone (please complete the following information):

sosauce commented 6 months ago

Noted ! May I ask why wpuld try calcupate the sqrt of a negative number knowing its mathematically impossible ? 🤔

Ransomware3301 commented 6 months ago

It is mathematically impossible when we work with real numbers, since the function $f(x) = \sqrt{x}\space$ isn't defined for negative numbers, but if you take into account complex numbers, then you have the imaginary unit, defined as $i = \sqrt{-1}$ and this enables you to calculate for example: $\sqrt{-3}$ as $i\sqrt{3}$, thus eliminating the negative value in the radicand.

Although, since you've not yet implemented the advanced/scientific mode, you don't have to worry about it, just put a check for $x \geq 0$ and you're good to go.

Keep up the good work!

sosauce commented 6 months ago

Oof, imma be honest I suck at maths, thanks ! :)

notKamui commented 6 months ago

@sosauce to solve this

first create a custom exception like class NegativeSquareRootException : RuntimeException("negative square root")

then in the definition of the operator you can do

unaryOperator {
    symbol = '√'
    isPrefix = true
    implementation = { arg -> if (arg < 0) throw NegativeSquareRootException() else sqrt(arg) }
}

And finally you can do something like this in the eval function

    fun eval(formula: String): String = try {
        KEVAL.eval(formula).toBigDecimal().stripTrailingZeros().toPlainString()
    } catch (e: KevalZeroDivisionException) {
        "Undefined (zero division)"
    } catch (e: NegativeSquareRootException) {
        "Undefined in Reals (negative square root)"
    } catch (e: KevalException) {
        "Error"
    }
realeatham commented 6 months ago

You should update the default sqrt unary operator in keval to throw NegativeSquareRootException @notKamui

notKamui commented 6 months ago

You should update the default sqrt unary operator in keval to throw NegativeSquareRootException @notKamui

good catch

sosauce commented 6 months ago

Thanks ;)