diff --git a/README.md b/README.md index 1e70a36..1d7753a 100644 --- a/README.md +++ b/README.md @@ -41,6 +41,7 @@ No ads. No tracking. No internet permission. Just a calculator. - ✅ Clean, minimal calculator with retro circular keys - ✅ Live results — see the answer as you type +- ✅ Scientific keys behind a slide-up handle — sin, cos, tan (and inverses), ln, log, √, powers, π, e, factorial, DEG/RAD - ✅ Scrollable expression display — no more truncated numbers - ✅ Calculation history saved locally with Room database - ✅ Unit Converter — Length, Weight, Area, Volume, Temperature, Time, Speed, Pressure @@ -53,10 +54,11 @@ No ads. No tracking. No internet permission. Just a calculator. ## Screenshots

- - - - + + + + +

## Download diff --git a/app/build.gradle.kts b/app/build.gradle.kts index e1c4d2e..98920e6 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -17,8 +17,8 @@ android { applicationId = "com.rr.numio" minSdk = 24 targetSdk = 36 - versionCode = 9 - versionName = "1.0.8" + versionCode = 10 + versionName = "1.1.0" testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" } diff --git a/app/src/main/java/com/rr/numio/ui.CalculatorScreen.kt b/app/src/main/java/com/rr/numio/ui.CalculatorScreen.kt index c66bb4b..15105df 100644 --- a/app/src/main/java/com/rr/numio/ui.CalculatorScreen.kt +++ b/app/src/main/java/com/rr/numio/ui.CalculatorScreen.kt @@ -19,6 +19,14 @@ import androidx.compose.material.icons.filled.History import androidx.compose.material.icons.filled.Settings import androidx.compose.material3.* import androidx.compose.runtime.* +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.foundation.gestures.detectVerticalDragGestures +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.onClick +import androidx.compose.ui.semantics.role +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.unit.Dp import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.foundation.gestures.detectTapGestures @@ -49,6 +57,7 @@ private val NumioSurface = Color(0xFF3A3733) private val NumioRed = Color(0xFFE8452F) private val NumioTextMuted = Color(0xFF9C9578) private val NumioTextOnDark = Color(0xFFF2EFE9) +private val NumioSciSurface = Color(0xFF2A2825) @SuppressLint("UnusedBoxWithConstraintsScope") @OptIn(ExperimentalMaterial3Api::class) @@ -71,6 +80,9 @@ fun CalculatorScreen( var easterEggTapCount by remember { mutableIntStateOf(0) } var lastTapTime by remember { mutableLongStateOf(0L) } + // The scientific keys hide behind a handle; "2nd" swaps sin/cos/tan, ln/log for their inverses. + var panelOpen by rememberSaveable { mutableStateOf(false) } + var second by rememberSaveable { mutableStateOf(false) } val keys = listOf( listOf("AC" to KeyType.CLEAR_ALL, "C" to KeyType.BACKSPACE, "()" to KeyType.BRACKET, "%" to KeyType.OP, "÷" to KeyType.OP), @@ -170,21 +182,41 @@ fun CalculatorScreen( .fillMaxWidth() ) { if (maxWidth > maxHeight) { + val sciRowHeight = (maxHeight * 0.13f).coerceIn(28.dp, 40.dp) Row( modifier = Modifier.fillMaxSize(), horizontalArrangement = Arrangement.spacedBy(16.dp) ) { - CalcDisplay( - expression = uiState.expression, - result = uiState.result, - cursor = uiState.cursor, - showCursor = uiState.showCursor, - onTapExpression = { viewModel.moveCursor(it) }, - accentLight = accentLight, + // There's room in landscape, so the scientific keys are always shown + Column( modifier = Modifier .weight(1f) .fillMaxHeight() - ) + ) { + CalcDisplay( + expression = uiState.expression, + result = uiState.result, + cursor = uiState.cursor, + showCursor = uiState.showCursor, + onTapExpression = { viewModel.moveCursor(it) }, + accentLight = accentLight, + modifier = Modifier + .weight(1f) + .fillMaxWidth() + ) + SciPanel( + second = second, + degrees = uiState.degrees, + accent = accent, + rowHeight = sciRowHeight, + onToggleSecond = { second = !second }, + onToggleAngle = { viewModel.toggleAngleMode() }, + onKey = { viewModel.onKeyPress(it) }, + modifier = Modifier + .fillMaxWidth() + .padding(bottom = 16.dp) + ) + } CalcKeypad( keys = keys, accent = accent, @@ -210,11 +242,35 @@ fun CalculatorScreen( .weight(1f) .fillMaxWidth() ) + SciHandle( + open = panelOpen, + accent = accent, + onSetOpen = { panelOpen = it } + ) + AnimatedVisibility( + visible = panelOpen, + enter = expandVertically(tween(220)) + fadeIn(tween(220)), + exit = shrinkVertically(tween(180)) + fadeOut(tween(180)) + ) { + SciPanel( + second = second, + degrees = uiState.degrees, + accent = accent, + rowHeight = 44.dp, + onToggleSecond = { second = !second }, + onToggleAngle = { viewModel.toggleAngleMode() }, + onKey = { viewModel.onKeyPress(it) }, + modifier = Modifier + .fillMaxWidth() + .padding(bottom = 8.dp) + ) + } CalcKeypad( keys = keys, accent = accent, accentLight = NumioYellowLight, - heightShare = 0.65f, + // With the panel open the display gives up space so the keys keep their size + heightShare = if (panelOpen) 0.75f else 0.65f, onKey = { viewModel.onKeyPress(it) }, modifier = Modifier.fillMaxWidth() ) @@ -372,6 +428,123 @@ private fun CircleKey( } } +private class SciKeySpec(val label: String, val highlighted: Boolean, val onClick: () -> Unit) + +/** The scientific keys: 5 across, 3 rows. "2nd" swaps in the inverse functions for one key press. */ +@Composable +private fun SciPanel( + second: Boolean, + degrees: Boolean, + accent: Color, + rowHeight: Dp, + onToggleSecond: () -> Unit, + onToggleAngle: () -> Unit, + onKey: (String) -> Unit, + modifier: Modifier = Modifier +) { + fun plain(label: String) = SciKeySpec(label, false) { onKey(label) } + fun swapped(label: String, inverse: String) = if (second) { + SciKeySpec(inverse, false) { + onKey(inverse) + onToggleSecond() + } + } else { + plain(label) + } + + val rows = listOf( + listOf( + SciKeySpec("2nd", second, onToggleSecond), + swapped("sin", "sin⁻¹"), + swapped("cos", "cos⁻¹"), + swapped("tan", "tan⁻¹"), + SciKeySpec(if (degrees) "DEG" else "RAD", false, onToggleAngle) + ), + listOf(swapped("ln", "eˣ"), swapped("log", "10ˣ"), plain("√"), plain("x²"), plain("xʸ")), + listOf(plain("π"), plain("e"), plain("!"), plain("1/x"), plain("|x|")) + ) + Column( + verticalArrangement = Arrangement.spacedBy(8.dp), + modifier = modifier + ) { + rows.forEach { row -> + Row( + horizontalArrangement = Arrangement.spacedBy(8.dp), + modifier = Modifier.fillMaxWidth() + ) { + row.forEach { spec -> + SciKey( + spec = spec, + accent = accent, + labelSize = (rowHeight.value * 0.42f).coerceIn(12f, 19f), + modifier = Modifier.weight(1f).height(rowHeight) + ) + } + } + } + } +} + +@Composable +private fun SciKey(spec: SciKeySpec, accent: Color, labelSize: Float, modifier: Modifier = Modifier) { + val isMode = spec.label == "2nd" || spec.label == "DEG" || spec.label == "RAD" + val fontScale = LocalDensity.current.fontScale + Box( + modifier = modifier + .clip(RoundedCornerShape(999.dp)) + .background(if (spec.highlighted) accent else NumioSciSurface) + .clickable(role = Role.Button, onClick = spec.onClick), + contentAlignment = Alignment.Center + ) { + Text( + text = spec.label, + color = if (spec.highlighted) NumioBg else if (isMode) accent else NumioTextOnDark, + // Keep the label the same size at big system fonts, so "sin⁻¹" is never cut off + fontSize = (labelSize / fontScale.coerceAtLeast(1f)).sp, + fontWeight = FontWeight.Medium, + maxLines = 1, + softWrap = false + ) + } +} + +/** Tap, or swipe up or down, to show or hide the scientific keys. */ +@Composable +private fun SciHandle(open: Boolean, accent: Color, onSetOpen: (Boolean) -> Unit) { + val label = if (open) "Hide scientific keys" else "Show scientific keys" + Box( + modifier = Modifier + .fillMaxWidth() + .height(28.dp) + .semantics { + contentDescription = label + role = Role.Button + onClick(label = label) { + onSetOpen(!open) + true + } + } + .pointerInput(open) { detectTapGestures { onSetOpen(!open) } } + .pointerInput(open) { + var total = 0f + detectVerticalDragGestures( + onDragStart = { total = 0f }, + onDragEnd = { + if (total < -24f) onSetOpen(true) else if (total > 24f) onSetOpen(false) + } + ) { _, delta -> total += delta } + }, + contentAlignment = Alignment.Center + ) { + Box( + modifier = Modifier + .size(width = 40.dp, height = 4.dp) + .clip(RoundedCornerShape(2.dp)) + .background(if (open) accent else NumioTextMuted.copy(alpha = 0.6f)) + ) + } +} + @Composable private fun HistoryOverlay(onDismiss: () -> Unit, content: @Composable () -> Unit) { BackHandler(onBack = onDismiss) diff --git a/app/src/main/java/com/rr/numio/ui.CalculatorViewModel.kt b/app/src/main/java/com/rr/numio/ui.CalculatorViewModel.kt index 8e58e6b..969c56e 100644 --- a/app/src/main/java/com/rr/numio/ui.CalculatorViewModel.kt +++ b/app/src/main/java/com/rr/numio/ui.CalculatorViewModel.kt @@ -14,11 +14,21 @@ import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch import net.objecthunter.exp4j.ExpressionBuilder -import net.objecthunter.exp4j.function.Function -private val sqrtFunction = object : Function("sqrt", 1) { - override fun apply(vararg args: Double): Double = kotlin.math.sqrt(args[0]) -} +/** What each scientific key types. A function key types its name and an opening bracket. */ +private val FUNCTION_KEYS = mapOf( + "sin" to "sin(", "cos" to "cos(", "tan" to "tan(", + "sin⁻¹" to "sin⁻¹(", "cos⁻¹" to "cos⁻¹(", "tan⁻¹" to "tan⁻¹(", + "ln" to "ln(", "log" to "log(", "√" to "√(", "|x|" to "abs(", + "eˣ" to "e^(", "10ˣ" to "10^(", "1/x" to "1÷(" +) + +/** Function names the cursor treats as one piece: ⌫ deletes all of "sin(", taps can't land inside it. */ +private val FUNCTION_NAMES = listOf("sin⁻¹(", "cos⁻¹(", "tan⁻¹(", "sin(", "cos(", "tan(", "ln(", "log(", "abs(", "√(") + +/** Characters that mean the old exp4j fallback can't be trusted (it would work in radians). */ +private fun hasScientificSymbols(expression: String) = + expression.any { it in 'a'..'z' || it == 'π' || it == '√' || it == '²' || it == '!' } data class CalculatorUiState( val expression: String = "", @@ -27,6 +37,8 @@ data class CalculatorUiState( val cursor: Int = 0, /** True after tapping the expression: the cursor stays visible (even at the end) until = or AC. */ val showCursor: Boolean = false, + /** True: sin, cos and tan work in degrees; false: in radians. */ + val degrees: Boolean = true, val isHistoryVisible: Boolean = false, val isEasterEggVisible: Boolean = false ) @@ -50,7 +62,8 @@ class CalculatorViewModel(application: Application) : AndroidViewModel(applicati private val operators = setOf("+", "-", "×", "÷", "^", "%") - fun onKeyPress(label: String) { + fun onKeyPress(key: String) { + val label = if (key == "xʸ") "^" else key val current = _uiState.value val cursor = current.cursor.coerceIn(0, current.expression.length) // Keys work on the text left of the cursor; the text right of it stays as it is. @@ -63,7 +76,9 @@ class CalculatorViewModel(application: Application) : AndroidViewModel(applicati } "C" -> { justEvaluated = false - val newBefore = before.dropLast(1) + // A function like "sin(" goes in one tap + val cut = FUNCTION_NAMES.firstOrNull { before.endsWith(it) }?.length ?: 1 + val newBefore = before.dropLast(cut) val newExpr = newBefore + after _uiState.value = current.copy( expression = newExpr, @@ -73,7 +88,8 @@ class CalculatorViewModel(application: Application) : AndroidViewModel(applicati } "=" -> evaluate() else -> { - val isOperator = label in operators + // x² and ! carry on from the last answer, like an operator + val isOperator = label in operators || label == "x²" || label == "!" val (base, rest) = when { justEvaluated && isOperator -> (if (current.result.isNotEmpty() && current.result != "Error") current.result @@ -107,7 +123,7 @@ class CalculatorViewModel(application: Application) : AndroidViewModel(applicati /** Tapping the expression puts the cursor there, to fix or add a number in the middle. */ fun moveCursor(position: Int) { val current = _uiState.value - val newCursor = position.coerceIn(0, current.expression.length) + val newCursor = snapOutOfFunction(current.expression, position.coerceIn(0, current.expression.length)) if (newCursor == current.cursor && current.showCursor && !justEvaluated) return justEvaluated = false _uiState.value = current.copy( @@ -117,19 +133,54 @@ class CalculatorViewModel(application: Application) : AndroidViewModel(applicati ) } + /** A tap in the middle of "sin(" moves to the nearer side of it, so a function is never split. */ + private fun snapOutOfFunction(expression: String, position: Int): Int { + var i = 0 + while (i < expression.length) { + val name = FUNCTION_NAMES.firstOrNull { expression.startsWith(it, i) } + if (name == null) { + i++ + continue + } + val end = i + name.length + if (position > i && position < end) return if (position - i < end - position) i else end + i = end + } + return position + } + + fun toggleAngleMode() { + val current = _uiState.value + val switched = current.copy(degrees = !current.degrees) + _uiState.value = switched.copy(result = evaluatePreview(current.expression, switched.degrees)) + } + private val binaryOps = setOf("+", "-", "×", "÷", "^") private fun appendInput(expr: String, label: String): String { val last = expr.lastOrNull()?.toString() // After % or ) a new number means multiply: 5%2 → 5%×2, (2+3)4 → (2+3)×4 - val afterClosed = last == "%" || last == ")" + // The same after π, e, ² and ! + val afterClosed = last == "%" || last == ")" || last == "π" || last == "e" || last == "²" || last == "!" return when { + label in FUNCTION_KEYS || label == "π" || label == "e" -> { + // Right after a value, a function or constant multiplies: 2π → 2×π, 3sin( → 3×sin( + val text = FUNCTION_KEYS[label] ?: label + val t = expr.trimEnd('.') + val afterValue = t.lastOrNull()?.let { it.isDigit() || it in ")%πe²!" } == true + if (afterValue) "$t×$text" else expr + text + } + label == "x²" || label == "!" -> { + val t = expr.trimEnd('.') + val afterValue = t.lastOrNull()?.let { it.isDigit() || it in ")%πe²!" } == true + if (afterValue) t + (if (label == "x²") "²" else "!") else expr + } label == "()" -> { // One smart key: closes an open bracket after a number, otherwise opens one. // A bracket right after a number multiplies: 2( → 2×( val stillOpen = expr.count { it == '(' } - expr.count { it == ')' } val c = expr.lastOrNull() - val afterValue = c != null && (c.isDigit() || c == ')' || c == '%' || c == '.') + val afterValue = c != null && (c.isDigit() || c in ").%πe²!") when { stillOpen > 0 && afterValue -> expr.trimEnd('.') + ")" afterValue -> expr.trimEnd('.') + "×(" @@ -193,7 +244,7 @@ class CalculatorViewModel(application: Application) : AndroidViewModel(applicati if (trailingOperator.containsMatchIn(expr)) return false // Editing in the middle can leave broken spots, like deleting the 1 in 45-1+124 // gives 45-+124. Show no answer until it's fixed, instead of a wrong one. - if (expr.first() in "+×÷^%)") return false + if (expr.first() in "+×÷^%)²!") return false for (i in 1 until expr.length) { val a = expr[i - 1] val b = expr[i] @@ -203,7 +254,7 @@ class CalculatorViewModel(application: Application) : AndroidViewModel(applicati b in "+×÷^" && (aIsOp || a == '(') -> return false b == '-' && a in "+-" -> return false // % or ) right after a sign or "(" - (b == '%' || b == ')') && (aIsOp || a == '(') -> return false + b in "%)²!" && (aIsOp || a == '(') -> return false } } return true @@ -215,9 +266,9 @@ class CalculatorViewModel(application: Application) : AndroidViewModel(applicati return if (stillOpen > 0) expr + ")".repeat(stillOpen) else expr } - private fun evaluatePreview(expression: String): String { + private fun evaluatePreview(expression: String, degrees: Boolean = _uiState.value.degrees): String { if (!isCompleteExpression(expression)) return "" - return calculate(closeBrackets(expression)) ?: "" + return calculate(closeBrackets(expression), degrees) ?: "" } private fun evaluate() { @@ -227,7 +278,7 @@ class CalculatorViewModel(application: Application) : AndroidViewModel(applicati return } val expression = closeBrackets(typed) - val resStr = calculate(expression) + val resStr = calculate(expression, _uiState.value.degrees) if (resStr == null) { _uiState.value = _uiState.value.copy(result = "Error") return @@ -250,17 +301,17 @@ class CalculatorViewModel(application: Application) : AndroidViewModel(applicati * Keypad maths is done exactly (see [ExactMath]); exp4j is only the fallback, * e.g. for a result like 1.5E20 reused from history. */ - private fun calculate(expression: String): String? { - ExactMath.evaluate(expression)?.let { return formatExact(it) } + private fun calculate(expression: String, degrees: Boolean): String? { + ExactMath.evaluate(expression, degrees)?.let { return formatExact(it) } + // Anything with sin, ln, π and so on that ExactMath refused is an error, not a job for exp4j + if (hasScientificSymbols(expression)) return null return try { val sanitized = expression .replace("×", "*") .replace("÷", "/") .replace("%", "/100") - .replace(Regex("√(\\d+(\\.\\d+)?)"), "sqrt($1)") val res = ExpressionBuilder(sanitized) - .function(sqrtFunction) .build() .evaluate() diff --git a/app/src/main/java/com/rr/numio/ui.ExactMath.kt b/app/src/main/java/com/rr/numio/ui.ExactMath.kt index faf757c..12560fd 100644 --- a/app/src/main/java/com/rr/numio/ui.ExactMath.kt +++ b/app/src/main/java/com/rr/numio/ui.ExactMath.kt @@ -5,24 +5,39 @@ import java.math.MathContext import java.util.Locale /** - * Exact maths for what the keypad can type: numbers, + - × ÷ % and brackets. + * Exact maths for what the keypad can type: numbers, + - × ÷ % ^ ² ! brackets, π, e and the + * scientific functions (sin cos tan and their inverses, ln, log, √, abs). * * exp4j works in Double, which only keeps about 16 digits, so * 9007199254740993 − 9007199254740992 came out as 0 instead of 1. * BigDecimal keeps every digit for + − × and 34 digits for ÷. + * Functions like sin or ln have no exact form, so they are worked out in Double and + * rounded to 15 digits (sin 30° gives 0.5, not 0.49999999999999994). * * Returns null when the text has anything else in it (like 1.5E20 reused from history) - * or can't be worked out (like ÷ 0), so the caller can fall back to exp4j. + * or can't be worked out (like ÷ 0 or ln(-1)), so the caller can show an error. */ internal object ExactMath { private val DIVIDE = MathContext.DECIMAL128 + private val ROUND = MathContext(15) private val HUNDRED = BigDecimal(100) - private const val ALLOWED = "0123456789.+-×÷%()" + private val FULL_TURN = BigDecimal(360) + private val QUARTER_TURN = BigDecimal(90) + private val PI = BigDecimal("3.14159265358979323846264338327950288") + private val E = BigDecimal("2.71828182845904523536028747135266250") + private const val BASIC = "0123456789.+-×÷%()^²!" + private const val MAX_FACTORIAL = 1000 + private const val MAX_INTEGER_POWER = 9999 - fun evaluate(expression: String): BigDecimal? { - if (expression.isEmpty() || expression.any { it !in ALLOWED }) return null + /** Longest first, so "sin⁻¹" is not read as "sin". Each is followed by "(". */ + private val FUNCTIONS = listOf("sin⁻¹", "cos⁻¹", "tan⁻¹", "sin", "cos", "tan", "ln", "log", "abs", "√") + + private fun allowed(c: Char) = c in BASIC || c in 'a'..'z' || c == 'π' || c == '√' || c == '⁻' || c == '¹' + + fun evaluate(expression: String, degrees: Boolean = true): BigDecimal? { + if (expression.isEmpty() || !expression.all { allowed(it) }) return null return try { - Parser(expression).parse() + Parser(expression, degrees).parse() } catch (e: NumberFormatException) { null } catch (e: ArithmeticException) { @@ -32,9 +47,10 @@ internal object ExactMath { /** * expression := term (+|- term)* ; term := unary (×|÷ unary)* - * unary := -unary | (number | "(" expression ")") %* + * unary := -unary | power ; power := postfix (^ unary)? + * postfix := atom (% | ² | !)* ; atom := number | π | e | ( expression ) | name ( expression ) */ - private class Parser(private val s: String) { + private class Parser(private val s: String, private val degrees: Boolean) { private var pos = 0 fun parse(): BigDecimal { @@ -70,19 +86,55 @@ internal object ExactMath { pos++ return unary().negate() } - var value = if (peek() == '(') { - pos++ - val inside = expression() - if (peek() != ')') throw NumberFormatException("Missing ) at $pos") + return power() + } + + private fun power(): BigDecimal { + val base = postfix() + if (peek() == '^') { pos++ - inside - } else { - number() + return pow(base, unary()) } - while (peek() == '%') { + return base + } + + private fun postfix(): BigDecimal { + var value = atom() + while (true) { + value = when (peek()) { + '%' -> value.divide(HUNDRED, DIVIDE) + '²' -> value.multiply(value) + '!' -> factorial(value) + else -> return value + } pos++ - value = value.divide(HUNDRED, DIVIDE) } + } + + private fun atom(): BigDecimal { + val c = peek() ?: throw NumberFormatException("Unexpected end") + return when { + c == '(' -> { + pos++ + closeBracket(expression()) + } + c == 'π' -> { pos++; PI } + c == 'e' -> { pos++; E } + c in '0'..'9' || c == '.' -> number() + else -> { + val name = FUNCTIONS.firstOrNull { s.startsWith(it, pos) } + ?: throw NumberFormatException("Unknown '$c' at $pos") + pos += name.length + if (peek() != '(') throw NumberFormatException("Missing ( after $name") + pos++ + callFunction(name, closeBracket(expression())) + } + } + } + + private fun closeBracket(value: BigDecimal): BigDecimal { + if (peek() != ')') throw NumberFormatException("Missing ) at $pos") + pos++ return value } @@ -92,6 +144,95 @@ internal object ExactMath { if (start == pos) throw NumberFormatException("Number expected at $start") return BigDecimal(s.substring(start, pos)) } + + private fun callFunction(name: String, x: BigDecimal): BigDecimal = when (name) { + "sin", "cos", "tan" -> trig(name, x) + "sin⁻¹", "cos⁻¹", "tan⁻¹" -> inverseTrig(name, x) + "ln" -> { + if (x.signum() <= 0) throw ArithmeticException("ln of $x") + fromDouble(Math.log(x.toDouble())) + } + "log" -> { + if (x.signum() <= 0) throw ArithmeticException("log of $x") + fromDouble(Math.log10(x.toDouble())) + } + "√" -> { + if (x.signum() < 0) throw ArithmeticException("√ of $x") + fromDouble(Math.sqrt(x.toDouble())) + } + "abs" -> x.abs() + else -> throw NumberFormatException("Unknown function $name") + } + + private fun trig(name: String, x: BigDecimal): BigDecimal { + val radians: Double + if (degrees) { + var turn = x.remainder(FULL_TURN) + if (turn.signum() < 0) turn = turn.add(FULL_TURN) + // 0°, 90°, 180°, 270° are exact: sin 180° is 0, not 1.2E-16 + if (turn.remainder(QUARTER_TURN).signum() == 0) { + val quarter = turn.toInt() / 90 + return BigDecimal( + when (name) { + "sin" -> intArrayOf(0, 1, 0, -1)[quarter] + "cos" -> intArrayOf(1, 0, -1, 0)[quarter] + else -> { + if (quarter % 2 == 1) throw ArithmeticException("tan of 90°") + 0 + } + } + ) + } + radians = Math.toRadians(turn.toDouble()) + } else { + radians = x.toDouble() + } + val value = when (name) { + "sin" -> Math.sin(radians) + "cos" -> Math.cos(radians) + else -> Math.tan(radians) + } + if (Math.abs(value) < 1e-15 && Math.abs(radians) > 1e-3) return BigDecimal.ZERO + if (Math.abs(value) > 1e15) throw ArithmeticException("$name is undefined here") + return fromDouble(value) + } + + private fun inverseTrig(name: String, x: BigDecimal): BigDecimal { + val v = x.toDouble() + if (name != "tan⁻¹" && (v < -1.0 || v > 1.0)) throw ArithmeticException("$name of $x") + val radians = when (name) { + "sin⁻¹" -> Math.asin(v) + "cos⁻¹" -> Math.acos(v) + else -> Math.atan(v) + } + return fromDouble(if (degrees) Math.toDegrees(radians) else radians) + } + + private fun pow(base: BigDecimal, exponent: BigDecimal): BigDecimal { + val whole = exponent.stripTrailingZeros().scale() <= 0 + if (whole && exponent.abs() <= BigDecimal(MAX_INTEGER_POWER)) { + val n = exponent.toInt() + val p = base.pow(Math.abs(n), DIVIDE) + return if (n >= 0) p else BigDecimal.ONE.divide(p, DIVIDE) + } + return fromDouble(Math.pow(base.toDouble(), exponent.toDouble())) + } + + private fun factorial(x: BigDecimal): BigDecimal { + val n = x.toBigIntegerExact() + if (n.signum() < 0 || n > java.math.BigInteger.valueOf(MAX_FACTORIAL.toLong())) { + throw ArithmeticException("factorial of $x") + } + var result = java.math.BigInteger.ONE + for (i in 2..n.toInt()) result = result.multiply(java.math.BigInteger.valueOf(i.toLong())) + return BigDecimal(result) + } + + /** A Double result as a 15-digit BigDecimal; null-like cases (NaN, ∞) are errors. */ + private fun fromDouble(d: Double): BigDecimal { + if (d.isNaN() || d.isInfinite()) throw ArithmeticException("not a number") + return BigDecimal.valueOf(d).round(ROUND) + } } } diff --git a/app/src/test/java/com/rr/numio/ui/ExactMathTest.kt b/app/src/test/java/com/rr/numio/ui/ExactMathTest.kt index f036170..66f4d2a 100644 --- a/app/src/test/java/com/rr/numio/ui/ExactMathTest.kt +++ b/app/src/test/java/com/rr/numio/ui/ExactMathTest.kt @@ -6,8 +6,8 @@ import org.junit.Test class ExactMathTest { - private fun calc(expression: String): String? = - ExactMath.evaluate(expression)?.let { formatExact(it) } + private fun calc(expression: String, degrees: Boolean = true): String? = + ExactMath.evaluate(expression, degrees)?.let { formatExact(it) } @Test fun bigNumbersKeepEveryDigit() { @@ -62,4 +62,98 @@ class ExactMathTest { assertNull(ExactMath.evaluate("2+")) assertNull(ExactMath.evaluate("")) } + + @Test + fun trigInDegrees() { + assertEquals("0.5", calc("sin(30)")) + assertEquals("1", calc("sin(90)")) + assertEquals("0", calc("sin(180)")) + assertEquals("-1", calc("sin(270)")) + assertEquals("0.5", calc("cos(60)")) + assertEquals("0", calc("cos(90)")) + assertEquals("1", calc("tan(45)")) + assertEquals("0", calc("tan(180)")) + assertEquals("0.5", calc("sin(390)")) + assertEquals("-0.5", calc("sin(-30)")) + assertNull(calc("tan(90)")) + assertNull(calc("tan(270)")) + } + + @Test + fun trigInRadians() { + assertEquals("1", calc("sin(π÷2)", degrees = false)) + assertEquals("0", calc("sin(π)", degrees = false)) + assertEquals("-1", calc("cos(π)", degrees = false)) + assertEquals("0.841470984807897", calc("sin(1)", degrees = false)) + } + + @Test + fun inverseTrig() { + assertEquals("30", calc("sin⁻¹(0.5)")) + assertEquals("90", calc("cos⁻¹(0)")) + assertEquals("45", calc("tan⁻¹(1)")) + assertEquals("1.5707963267949", calc("sin⁻¹(1)", degrees = false)) + assertNull(calc("sin⁻¹(2)")) + assertNull(calc("cos⁻¹(-2)")) + } + + @Test + fun logsAndRoots() { + assertEquals("0", calc("ln(1)")) + assertEquals("1", calc("ln(e)")) + assertEquals("3", calc("log(1000)")) + assertEquals("3", calc("√(9)")) + assertEquals("0.5", calc("√(0.25)")) + assertEquals("1.4142135623731", calc("√(2)")) + assertEquals("5", calc("abs(-5)")) + assertNull(calc("ln(0)")) + assertNull(calc("ln(-1)")) + assertNull(calc("log(0)")) + assertNull(calc("√(-4)")) + } + + @Test + fun powersFactorialsAndConstants() { + assertEquals("1024", calc("2^10")) + assertEquals("0.5", calc("2^-1")) + assertEquals("0.25", calc("2^-2")) + assertEquals("512", calc("2^3^2")) + assertEquals("-4", calc("-2^2")) + assertEquals("1.4142135623731", calc("2^0.5")) + assertEquals("20", calc("(2+3)^2×0.8")) + assertNull(calc("0^-1")) + assertNull(calc("(-8)^(1÷3)")) + assertEquals("25", calc("5²")) + assertEquals("2.25", calc("1.5²")) + assertEquals("10", calc("3²+1")) + assertEquals("120", calc("5!")) + assertEquals("1", calc("0!")) + assertEquals("2432902008176640000", calc("20!")) + assertNull(calc("3.5!")) + assertNull(calc("(0-1)!")) + assertNull(calc("1001!")) + assertEquals("3.14159265358979", calc("π")) + assertEquals("2.71828182845905", calc("e")) + assertEquals("6.28318530717959", calc("2×π")) + assertEquals("2.71828182845905", calc("e^(1)")) + } + + @Test + fun scientificMixedWithEverydayMaths() { + assertEquals("4", calc("2×sin(30)+√(9)")) + assertEquals("0.25", calc("1÷(4)")) + assertEquals("100", calc("10^(2)")) + assertEquals("1", calc("sin(30)+cos(60)")) + assertEquals("7", calc("(3+4)×sin(90)")) + } + + @Test + fun brokenScientificInputIsRefused() { + assertNull(calc("sin(30")) // the screen adds the missing ")" first + assertNull(calc("sin30")) + assertNull(calc("sin()")) + assertNull(calc("foo(3)")) + assertNull(calc("2π")) // the keypad types 2×π + assertNull(calc("5!!!x")) + } } diff --git a/fastlane/metadata/android/en-US/changelogs/10.txt b/fastlane/metadata/android/en-US/changelogs/10.txt new file mode 100644 index 0000000..3721ac2 --- /dev/null +++ b/fastlane/metadata/android/en-US/changelogs/10.txt @@ -0,0 +1,3 @@ +- Scientific keys: swipe up the handle for sin, cos, tan (2nd for inverses), ln, log, √, x², xʸ, π, e, !, 1/x, |x| and DEG/RAD +- Functions go in and out in one tap with ⌫ +- Always shown in landscape diff --git a/fastlane/metadata/android/en-US/full_description.txt b/fastlane/metadata/android/en-US/full_description.txt index 1882492..03ebc7c 100644 --- a/fastlane/metadata/android/en-US/full_description.txt +++ b/fastlane/metadata/android/en-US/full_description.txt @@ -4,6 +4,7 @@ Features: * Clean, minimal design with retro circular keys * Live results — see the answer as you type +* Scientific keys behind a slide-up handle — sin, cos, tan, ln, log, √, powers, π, e, factorial, DEG/RAD * Scrollable expression display, so long numbers are never truncated * Calculation history saved locally with a Room database * Built-in unit converter — Length, Weight, Area, Volume, Temperature, Time, Speed, Pressure diff --git a/fastlane/metadata/android/en-US/images/phoneScreenshots/1.jpg b/fastlane/metadata/android/en-US/images/phoneScreenshots/1.jpg index fb2ae23..1d07212 100644 Binary files a/fastlane/metadata/android/en-US/images/phoneScreenshots/1.jpg and b/fastlane/metadata/android/en-US/images/phoneScreenshots/1.jpg differ diff --git a/fastlane/metadata/android/en-US/images/phoneScreenshots/2.jpg b/fastlane/metadata/android/en-US/images/phoneScreenshots/2.jpg index 73d98f1..92afda7 100644 Binary files a/fastlane/metadata/android/en-US/images/phoneScreenshots/2.jpg and b/fastlane/metadata/android/en-US/images/phoneScreenshots/2.jpg differ diff --git a/fastlane/metadata/android/en-US/images/phoneScreenshots/3.jpg b/fastlane/metadata/android/en-US/images/phoneScreenshots/3.jpg index a606253..73d98f1 100644 Binary files a/fastlane/metadata/android/en-US/images/phoneScreenshots/3.jpg and b/fastlane/metadata/android/en-US/images/phoneScreenshots/3.jpg differ diff --git a/fastlane/metadata/android/en-US/images/phoneScreenshots/4.jpg b/fastlane/metadata/android/en-US/images/phoneScreenshots/4.jpg index 1a5fd21..6458037 100644 Binary files a/fastlane/metadata/android/en-US/images/phoneScreenshots/4.jpg and b/fastlane/metadata/android/en-US/images/phoneScreenshots/4.jpg differ diff --git a/fastlane/metadata/android/en-US/images/phoneScreenshots/5.jpg b/fastlane/metadata/android/en-US/images/phoneScreenshots/5.jpg new file mode 100644 index 0000000..c65775f Binary files /dev/null and b/fastlane/metadata/android/en-US/images/phoneScreenshots/5.jpg differ diff --git a/screenshots/Numio1.jpg b/screenshots/Numio1.jpg index fb2ae23..1d07212 100644 Binary files a/screenshots/Numio1.jpg and b/screenshots/Numio1.jpg differ diff --git a/screenshots/Numio2.jpg b/screenshots/Numio2.jpg index 73d98f1..92afda7 100644 Binary files a/screenshots/Numio2.jpg and b/screenshots/Numio2.jpg differ diff --git a/screenshots/Numio3.jpg b/screenshots/Numio3.jpg index a606253..73d98f1 100644 Binary files a/screenshots/Numio3.jpg and b/screenshots/Numio3.jpg differ diff --git a/screenshots/Numio4.jpg b/screenshots/Numio4.jpg index 1a5fd21..6458037 100644 Binary files a/screenshots/Numio4.jpg and b/screenshots/Numio4.jpg differ diff --git a/screenshots/Numio5.jpg b/screenshots/Numio5.jpg new file mode 100644 index 0000000..c65775f Binary files /dev/null and b/screenshots/Numio5.jpg differ