Spaces:
Sleeping
Sleeping
File size: 6,510 Bytes
3f2176f |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 |
import math
import streamlit as st
st.set_page_config(page_title="Calculator", page_icon="🧮", layout="centered")
# ---- Helpers ----
def safe_div(a, b):
if b == 0:
raise ZeroDivisionError("Cannot divide by zero")
return a / b
def fmt(x):
try:
# Show ints without .0
return int(x) if float(x).is_integer() else x
except Exception:
return x
def add_history(expr, result):
st.session_state.setdefault("history", [])
st.session_state.history.insert(0, f"{expr} = {result}")
# keep last 20
st.session_state.history = st.session_state.history[:20]
# ---- Sidebar ----
with st.sidebar:
st.header("⚙️ Options")
theme = st.radio("Mode", ["Basic", "Scientific"], horizontal=True)
show_history = st.checkbox("Show history", True)
st.markdown("---")
st.caption("Tip: Use the Basic tab for two number math. Use Scientific for single number functions and powers.")
st.title("🧮 Streamlit Calculator")
st.write("A simple calculator ready for Hugging Face Spaces.")
# ---- Basic Calculator ----
if theme == "Basic":
col1, col2 = st.columns(2)
with col1:
a = st.number_input("First number (a)", value=0.0, step=1.0, format="%.10f")
with col2:
b = st.number_input("Second number (b)", value=0.0, step=1.0, format="%.10f")
op = st.selectbox(
"Operation",
["+", "-", "×", "÷", "a^b (power)", "a % b (mod)"],
index=0
)
if st.button("Calculate", use_container_width=True):
try:
if op == "+":
result = a + b
expr = f"{a} + {b}"
elif op == "-":
result = a - b
expr = f"{a} - {b}"
elif op == "×":
result = a * b
expr = f"{a} × {b}"
elif op == "÷":
result = safe_div(a, b)
expr = f"{a} ÷ {b}"
elif op == "a^b (power)":
result = math.pow(a, b)
expr = f"{a}^{b}"
elif op == "a % b (mod)":
if b == 0:
raise ZeroDivisionError("Cannot mod by zero")
result = a % b
expr = f"{a} % {b}"
else:
raise ValueError("Unknown operation")
result_fmt = fmt(result)
st.success(f"Result: {result_fmt}")
add_history(expr, result_fmt)
except Exception as e:
st.error(f"Error: {e}")
# ---- Scientific Calculator ----
else:
col_a, col_b = st.columns([2, 1])
with col_a:
x = st.number_input("Value (x)", value=0.0, step=1.0, format="%.10f")
with col_b:
use_degrees = st.checkbox("Trig in degrees", True)
func = st.selectbox(
"Function",
[
"sin(x)", "cos(x)", "tan(x)",
"asin(x)", "acos(x)", "atan(x)",
"ln(x)", "log10(x)", "sqrt(x)",
"exp(x)", "abs(x)", "factorial(x) (non negative integer)",
"x^n (power)"
],
index=0
)
n = None
if func == "x^n (power)":
n = st.number_input("Exponent (n)", value=2.0, step=1.0, format="%.10f")
if st.button("Calculate", use_container_width=True):
try:
val = x
angle = math.radians(x) if use_degrees else x
if func == "sin(x)":
res = math.sin(angle)
expr = f"sin({x}{'°' if use_degrees else ''})"
elif func == "cos(x)":
res = math.cos(angle)
expr = f"cos({x}{'°' if use_degrees else ''})"
elif func == "tan(x)":
res = math.tan(angle)
expr = f"tan({x}{'°' if use_degrees else ''})"
elif func == "asin(x)":
if val < -1 or val > 1:
raise ValueError("asin domain is [-1, 1]")
ang = math.asin(val)
res = math.degrees(ang) if use_degrees else ang
expr = f"asin({x})"
elif func == "acos(x)":
if val < -1 or val > 1:
raise ValueError("acos domain is [-1, 1]")
ang = math.acos(val)
res = math.degrees(ang) if use_degrees else ang
expr = f"acos({x})"
elif func == "atan(x)":
ang = math.atan(val)
res = math.degrees(ang) if use_degrees else ang
expr = f"atan({x})"
elif func == "ln(x)":
if val <= 0:
raise ValueError("ln domain is x > 0")
res = math.log(val)
expr = f"ln({x})"
elif func == "log10(x)":
if val <= 0:
raise ValueError("log10 domain is x > 0")
res = math.log10(val)
expr = f"log10({x})"
elif func == "sqrt(x)":
if val < 0:
raise ValueError("sqrt domain is x >= 0")
res = math.sqrt(val)
expr = f"√({x})"
elif func == "exp(x)":
res = math.exp(val)
expr = f"exp({x})"
elif func == "abs(x)":
res = abs(val)
expr = f"|{x}|"
elif func == "factorial(x) (non negative integer)":
if val < 0 or not float(val).is_integer():
raise ValueError("factorial requires a non negative integer")
res = math.factorial(int(val))
expr = f"{int(val)}!"
elif func == "x^n (power)":
res = math.pow(val, n)
expr = f"{val}^{n}"
else:
raise ValueError("Unknown function")
res_fmt = fmt(res)
st.success(f"Result: {res_fmt}")
add_history(expr, res_fmt)
except OverflowError:
st.error("Result overflowed for given input")
except Exception as e:
st.error(f"Error: {e}")
# ---- History ----
if show_history:
st.markdown("### 📝 History")
if st.session_state.get("history"):
for i, line in enumerate(st.session_state.history, 1):
st.code(f"{i}. {line}")
if st.button("Clear history"):
st.session_state.history = []
st.toast("History cleared")
else:
st.caption("No calculations yet")
# ---- Footer ----
st.markdown("---")
st.caption("Built with Streamlit. Ready for Hugging Face Spaces.")
|