the code has a bug where if i turn on e notation an type in for example: 1.56e+21 i get 1.56e+21 as result despite e notation being turned off. It also happens if afterwards i type in 1.56*10^21 where i get 1.56e+21 as result despite e notation being turned off. Python 3.12 code: import math
import re
from typing import Any, Union, Callable
from PySide6.QtWidgets import (
QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
QLineEdit, QTextEdit, QScrollBar, QPushButton, QLabel, QFrame,
QGridLayout
)
from PySide6.QtGui import QFont
from PySide6.QtCore import Qt, QSize
def convert_angle(func: Callable[[float], float], x: float, use_degrees: bool) -> float:
"""Apply trig function with optional degree conversion."""
return func(math.radians(x) if use_degrees else x)
def kilograms_to_pounds(kg: float) -> float:
"""Convert kilograms to pounds."""
return kg / 0.45359237
def capitalize_sentence(sentence: str) -> str:
"""Capitalize first letter of each word."""
return ' '.join(word.capitalize() for word in sentence.split())
def remove_duplicates(text: str) -> str:
"""Remove duplicate words and empty lines."""
words = ' '.join(line.strip() for line in text.splitlines() if line.strip()).split()
return ' '.join(dict.fromkeys(words))
def safe_evaluate(expression: str, safe_globals: dict, use_e_notation: bool) -> Union[str, Any]:
"""Safely evaluate expression and format result."""
try:
result = eval(expression, {"builtins": None}, safe_globals)
if isinstance(result, float) and abs(result) < 1e-10:
result = 0.0
if isinstance(result, (int, float)):
result = f"{result:.2e}" if use_e_notation else round(result, 2)
return result
except Exception as e:
return f"Error: {e}"
The code you provided is designed to handle numerical expressions and includes functionalities for toggling scientific notation and handling math and text functions. Based on your description, it seems the issue occurs because the expressions using scientific notation (e.g., 1.56e+21) are being evaluated and displayed consistently in scientific notation regardless of the toggled state.
Let's consider where the identified issue resides in your code:
Evaluation Function:
The evaluation is performed in the evaluate_expression and safe_evaluate functions. When safe_evaluate processes an expression, it checks the result type (int or float) and formats it according to the use_e_notation flag.
Formatting Float Results:
The formatting logic might not correctly account for converting scientific notation into standard decimal notation. The key part of this happens with these lines:
python
if isinstance(result, (int, float)):
result = f"{result:.2e}" if use_e_notation else round(result, 2)
Issues with round() on Large Numbers:
Using round(result, 2) directly on very large numbers might not display them correctly due to the limitations of floating-point representation, leading to no visible change.
To correct this, you could modify formatting logic by explicitly defining how large numbers should be shown if use_e_notation is turned off. Here's how you can enhance your code:
python
def safe_evaluate(expression: str, safe_globals: dict, use_e_notation: bool) -> Union[str, Any]:
"""Safely evaluate expression and format result."""
try:
result = eval(expression, {"__builtins__": None}, safe_globals)
# Fix to convert large floats to decimal notation when e-notation is turned off
if isinstance(result, float):
if abs(result) < 1e-10:
result = 0.0
if use_e_notation:
result = f"{result:.2e}"
else:
result = format(result, '.2f') if abs(result) < 1e+21 else '{:f}'.format(result)
elif isinstance(result, int):
pass # Ints should display correctly without scientific conversion.
return result
except Exception as e:
return f"Error: {e}"
Explanation:
Standard formatting for non-exponential:
The addition of format(result, '.2f') if abs(result) < 1e+21 else '{:f}'.format(result) converts large numbers to standard decimal notation wherever possible, maintaining precision for smaller numbers with format(result, '.2f').
Conditional Logic:
The formatting logic uses conditions to deal explicitly with very large numbers by leveraging {:.f} which forces a decimal layout, but this approach may not always maintain perfect precision for very high-magnitude floats (use with consideration of your application's precision requirements).
With this update, the application should better respect the user's setting for scientific notation and improve output consistency with user expectations.