Skip to content

Calculator Module

The Calculator module provides mathematical operations and calculation utilities. This module extends the BaseExample class and utilizes helper functions from the utilities module.

Overview

The Calculator class implements a comprehensive set of mathematical operations with proper error handling and input validation. All input validation is performed using the utility functions from the utils module.

Quick Reference

Method Purpose Related
add(a, b) Addition operation Uses validate_input from utils
subtract(a, b) Subtraction operation Inherits from BaseExample
multiply(a, b) Multiplication operation Output formatted with format_number from utils
divide(a, b) Division with zero-check See Error Handling

Usage Examples

Basic Operations

from src.example.calculator import Calculator
from src.example.utils import format_number

# Create calculator instance
calc = Calculator()

# Perform calculations
result = calc.add(10, 5)
formatted_result = format_number(result)
print(f"Result: {formatted_result}")

Advanced Usage

For more complex scenarios, see:

Configuration

The Calculator supports various configuration options:

# Custom configuration example
calc = Calculator(precision=4, validate_inputs=True)

For configuration details, see the utilities documentation.

Error Handling

The Calculator implements robust error handling patterns inherited from BaseExample:

  • Division by Zero: Handled gracefully with informative error messages
  • Invalid Input Types: Validated using utility functions from utils
  • Overflow Conditions: Proper handling of large number calculations

Integration

This module integrates with:

Testing

Comprehensive tests are available:

  • Unit tests for all mathematical operations
  • Edge case testing for error conditions
  • Integration tests with utility functions

See the test files for implementation details.

API Reference

Calculator module with mathematical operations.

This module provides calculator functionality with support for basic arithmetic operations and advanced mathematical functions.

Classes

Calculator

Calculator(precision: int = 4)

Advanced calculator with history tracking.

This calculator supports basic arithmetic operations and maintains a history of all calculations performed.

Attributes:

Name Type Description
history List[str]

List of calculation history entries

precision

Number of decimal places for results

Example
# Create calculator instance
calc = Calculator(precision=2)

# Perform calculations
result = calc.add(10, 5)  # 15.0
result = calc.multiply(3, 4)  # 12.0

# Check history
for entry in calc.history:
    print(entry)
Note

The calculator automatically rounds results based on the specified precision.

Initialize calculator with specified precision.

Parameters:

Name Type Description Default
precision int

Number of decimal places for results (default: 4)

4

Raises:

Type Description
ValueError

If precision is negative

Source code in src/example/calculator.py
def __init__(self, precision: int = 4) -> None:
    """Initialize calculator with specified precision.

    Args:
        precision: Number of decimal places for results (default: 4)

    Raises:
        ValueError: If precision is negative
    """
    if precision < 0:
        raise ValueError("Precision must be non-negative")

    self.history: List[str] = []
    self.precision = precision

Functions

add
add(a: Union[int, float], b: Union[int, float]) -> float

Add two numbers.

Parameters:

Name Type Description Default
a Union[int, float]

First number

required
b Union[int, float]

Second number

required

Returns:

Type Description
float

Sum of a and b

Example

calc = Calculator() calc.add(5, 3) 8.0

Source code in src/example/calculator.py
def add(self, a: Union[int, float], b: Union[int, float]) -> float:
    """Add two numbers.

    Args:
        a: First number
        b: Second number

    Returns:
        Sum of a and b

    Example:
        >>> calc = Calculator()
        >>> calc.add(5, 3)
        8.0
    """
    result = round(a + b, self.precision)
    self._record_operation(MathOperations.ADD, (a, b), result)
    return result
subtract
subtract(a: Union[int, float], b: Union[int, float]) -> float

Subtract b from a.

Parameters:

Name Type Description Default
a Union[int, float]

Number to subtract from

required
b Union[int, float]

Number to subtract

required

Returns:

Type Description
float

Difference of a and b

Example

calc = Calculator() calc.subtract(10, 4) 6.0

Source code in src/example/calculator.py
def subtract(self, a: Union[int, float], b: Union[int, float]) -> float:
    """Subtract b from a.

    Args:
        a: Number to subtract from
        b: Number to subtract

    Returns:
        Difference of a and b

    Example:
        >>> calc = Calculator()
        >>> calc.subtract(10, 4)
        6.0
    """
    result = round(a - b, self.precision)
    self._record_operation(MathOperations.SUBTRACT, (a, b), result)
    return result
multiply
multiply(a: Union[int, float], b: Union[int, float]) -> float

Multiply two numbers.

Parameters:

Name Type Description Default
a Union[int, float]

First factor

required
b Union[int, float]

Second factor

required

Returns:

Type Description
float

Product of a and b

Example

calc = Calculator() calc.multiply(3, 7) 21.0

Source code in src/example/calculator.py
def multiply(self, a: Union[int, float], b: Union[int, float]) -> float:
    """Multiply two numbers.

    Args:
        a: First factor
        b: Second factor

    Returns:
        Product of a and b

    Example:
        >>> calc = Calculator()
        >>> calc.multiply(3, 7)
        21.0
    """
    result = round(a * b, self.precision)
    self._record_operation(MathOperations.MULTIPLY, (a, b), result)
    return result
divide
divide(a: Union[int, float], b: Union[int, float]) -> float

Divide a by b.

Parameters:

Name Type Description Default
a Union[int, float]

Dividend

required
b Union[int, float]

Divisor

required

Returns:

Type Description
float

Quotient of a divided by b

Raises:

Type Description
ZeroDivisionError

If b is zero

Example

calc = Calculator() calc.divide(15, 3) 5.0

Source code in src/example/calculator.py
def divide(self, a: Union[int, float], b: Union[int, float]) -> float:
    """Divide a by b.

    Args:
        a: Dividend
        b: Divisor

    Returns:
        Quotient of a divided by b

    Raises:
        ZeroDivisionError: If b is zero

    Example:
        >>> calc = Calculator()
        >>> calc.divide(15, 3)
        5.0
    """
    if b == 0:
        raise ZeroDivisionError("Cannot divide by zero")

    result = round(a / b, self.precision)
    self._record_operation(MathOperations.DIVIDE, (a, b), result)
    return result
power
power(base: int, exponent: int) -> int
power(base: float, exponent: float) -> float
power(base: Union[int, float], exponent: Union[int, float]) -> Union[int, float]

Raise base to the power of exponent.

Parameters:

Name Type Description Default
base Union[int, float]

The base number

required
exponent Union[int, float]

The exponent

required

Returns:

Type Description
Union[int, float]

base raised to the power of exponent

Example

calc = Calculator() calc.power(2, 3) 8 calc.power(2.5, 2) 6.25

Source code in src/example/calculator.py
def power(
    self, base: Union[int, float], exponent: Union[int, float]
) -> Union[int, float]:
    """Raise base to the power of exponent.

    Args:
        base: The base number
        exponent: The exponent

    Returns:
        base raised to the power of exponent

    Example:
        >>> calc = Calculator()
        >>> calc.power(2, 3)
        8
        >>> calc.power(2.5, 2)
        6.25
    """
    result = base**exponent
    if isinstance(base, int) and isinstance(exponent, int) and exponent >= 0:
        self._record_operation(MathOperations.POWER, (base, exponent), result)
        return int(result)
    else:
        result = round(result, self.precision)
        self._record_operation(MathOperations.POWER, (base, exponent), result)
        return result
sqrt
sqrt(number: Union[int, float]) -> float

Calculate square root.

Parameters:

Name Type Description Default
number Union[int, float]

Number to find square root of

required

Returns:

Type Description
float

Square root of the number

Raises:

Type Description
ValueError

If number is negative

Example

calc = Calculator() calc.sqrt(16) 4.0

Source code in src/example/calculator.py
def sqrt(self, number: Union[int, float]) -> float:
    """Calculate square root.

    Args:
        number: Number to find square root of

    Returns:
        Square root of the number

    Raises:
        ValueError: If number is negative

    Example:
        >>> calc = Calculator()
        >>> calc.sqrt(16)
        4.0
    """
    if number < 0:
        raise ValueError("Cannot calculate square root of negative number")

    result = round(math.sqrt(number), self.precision)
    self._record_operation(MathOperations.ROOT, (number,), result)
    return result
clear_history
clear_history() -> None

Clear the calculation history.

Source code in src/example/calculator.py
def clear_history(self) -> None:
    """Clear the calculation history."""
    self.history.clear()
get_statistics
get_statistics() -> dict

Get statistics about calculator usage.

Returns:

Type Description
dict

Dictionary containing usage statistics including:

dict
  • total_operations: Total number of operations performed
dict
  • operation_counts: Count of each operation type
Example

calc = Calculator() calc.add(1, 2) 3.0 calc.multiply(3, 4) 12.0 stats = calc.get_statistics() stats['total_operations'] 2

Source code in src/example/calculator.py
def get_statistics(self) -> dict:
    """Get statistics about calculator usage.

    Returns:
        Dictionary containing usage statistics including:
        - total_operations: Total number of operations performed
        - operation_counts: Count of each operation type

    Example:
        >>> calc = Calculator()
        >>> calc.add(1, 2)
        3.0
        >>> calc.multiply(3, 4)
        12.0
        >>> stats = calc.get_statistics()
        >>> stats['total_operations']
        2
    """
    stats = {
        "total_operations": len(self.history),
        "operation_counts": {op.name: 0 for op in MathOperations},
    }

    for entry in self.history:
        for op in MathOperations:
            if op.value in entry:
                stats["operation_counts"][op.name] += 1
                break

    return stats