🧮 Scientific Calculator API

Complete REST API for mathematical and scientific calculations

https://www.promptbox.cn/api/calculator.php

📖 Overview

The Scientific Calculator API provides a comprehensive set of mathematical operations accessible via HTTP requests. All operations return JSON responses and support both GET and POST methods.

Features

✨ Basic Arithmetic

Addition, subtraction, multiplication, division, modulo, powers, and roots

📐 Trigonometry

Sin, cos, tan and their inverses. Support for degrees and radians

📊 Statistics

Mean, median, mode, variance, standard deviation, and more

🔢 Number Theory

GCD, LCM, prime checking, factorials, permutations, combinations

📈 Logarithmic

Natural log, log base 10, log base 2, custom bases, and exponentials

💯 Percentage

Calculate percentages, percentage of values, and percentage changes

🚀 Getting Started

Base URL

https://www.promptbox.cn/api/calculator.php

Request Format

All requests require an op parameter specifying the operation to perform.

Example Request:
GET https://www.promptbox.cn/api/calculator.php?op=add&a=5&b=3
Example Response:
{ "success": true, "operation": "add", "result": 8 }

HTTP Methods

  • GET - Pass parameters in URL query string
  • POST - Pass parameters in request body (form-data or JSON)

Response Format

All responses are returned in JSON format with the following structure:

Success Response:
{ "success": true, "operation": "operation_name", "result": value_or_object }
Error Response:
{ "success": false, "error": "Error message description" }

➕ Basic Operations

GET Addition

Operation: op=add

Parameters:

  • a (required) - First number
  • b (required) - Second number

Example:

?op=add&a=5&b=3 Result: 8
GET Subtraction

Operation: op=subtract

Parameters:

  • a (required) - First number
  • b (required) - Second number

Example:

?op=subtract&a=10&b=4 Result: 6
GET Multiplication

Operation: op=multiply

Parameters:

  • a (required) - First number
  • b (required) - Second number

Example:

?op=multiply&a=7&b=8 Result: 56
GET Division

Operation: op=divide

Parameters:

  • a (required) - Dividend
  • b (required) - Divisor (cannot be zero)

Example:

?op=divide&a=20&b=4 Result: 5
GET Modulo

Operation: op=modulo

Parameters:

  • a (required) - Number
  • b (required) - Divisor (cannot be zero)

Example:

?op=modulo&a=17&b=5 Result: 2
GET Power

Operation: op=power

Parameters:

  • base (required) - Base number
  • exponent (required) - Exponent

Example:

?op=power&base=2&exponent=8 Result: 256
GET Square Root

Operation: op=sqrt

Parameters:

  • n (required) - Number (must be non-negative)

Example:

?op=sqrt&n=144 Result: 12
GET Nth Root

Operation: op=nthRoot

Parameters:

  • n (required) - Number
  • root (required) - Root degree

Example:

?op=nthRoot&n=27&root=3 Result: 3
GET Absolute Value

Operation: op=abs

Parameters:

  • n (required) - Number

Example:

?op=abs&n=-15 Result: 15
GET Factorial

Operation: op=factorial

Parameters:

  • n (required) - Non-negative integer (max 170)

Example:

?op=factorial&n=5 Result: 120

📐 Trigonometric Functions

Note: All trigonometric functions support angle modes. Add angleMode=deg for degrees or angleMode=rad for radians (default).
GET Sine

Operation: op=sin

Parameters:

  • angle (required) - Angle value
  • angleMode (optional) - 'deg' or 'rad' (default: 'rad')

Example:

?op=sin&angle=90&angleMode=deg Result: 1
GET Cosine

Operation: op=cos

Parameters:

  • angle (required) - Angle value
  • angleMode (optional) - 'deg' or 'rad' (default: 'rad')

Example:

?op=cos&angle=0&angleMode=deg Result: 1
GET Tangent

Operation: op=tan

Parameters:

  • angle (required) - Angle value
  • angleMode (optional) - 'deg' or 'rad' (default: 'rad')

Example:

?op=tan&angle=45&angleMode=deg Result: 1
GET Arcsine

Operation: op=asin

Parameters:

  • value (required) - Value between -1 and 1
  • angleMode (optional) - 'deg' or 'rad' (default: 'rad')

Example:

?op=asin&value=0.5&angleMode=deg Result: 30
GET Arccosine

Operation: op=acos

Parameters:

  • value (required) - Value between -1 and 1
  • angleMode (optional) - 'deg' or 'rad' (default: 'rad')

Example:

?op=acos&value=0.5&angleMode=deg Result: 60
GET Arctangent

Operation: op=atan

Parameters:

  • value (required) - Any number
  • angleMode (optional) - 'deg' or 'rad' (default: 'rad')

Example:

?op=atan&value=1&angleMode=deg Result: 45
GET Arctangent2

Operation: op=atan2

Parameters:

  • y (required) - Y coordinate
  • x (required) - X coordinate
  • angleMode (optional) - 'deg' or 'rad' (default: 'rad')

Example:

?op=atan2&y=1&x=1&angleMode=deg Result: 45

Hyperbolic Functions

Operation Parameters Example
op=sinh x ?op=sinh&x=1
op=cosh x ?op=cosh&x=1
op=tanh x ?op=tanh&x=1
op=asinh x ?op=asinh&x=1
op=acosh x (≥1) ?op=acosh&x=2
op=atanh x (-1 < x < 1) ?op=atanh&x=0.5

📈 Logarithmic & Exponential Functions

GET Natural Logarithm (ln)

Operation: op=ln

Parameters:

  • n (required) - Positive number

Example:

?op=ln&n=2.718281828 Result: 1
GET Logarithm Base 10

Operation: op=log10

Parameters:

  • n (required) - Positive number

Example:

?op=log10&n=100 Result: 2
GET Logarithm Base 2

Operation: op=log2

Parameters:

  • n (required) - Positive number

Example:

?op=log2&n=8 Result: 3
GET Logarithm (Custom Base)

Operation: op=log

Parameters:

  • n (required) - Positive number
  • base (optional) - Base (default: e)

Example:

?op=log&n=81&base=3 Result: 4
GET Exponential (e^x)

Operation: op=exp

Parameters:

  • n (required) - Exponent

Example:

?op=exp&n=2 Result: 7.389056099

🔢 Rounding Functions

Operation Parameters Description Example
op=round n, precision (optional) Round to nearest value ?op=round&n=3.14159&precision=2 → 3.14
op=floor n Round down to integer ?op=floor&n=4.7 → 4
op=ceil n Round up to integer ?op=ceil&n=4.3 → 5

📊 Statistics Functions

Note: For statistics operations, pass arrays as comma-separated values or JSON arrays. Example: values=1,2,3,4,5 or values=[1,2,3,4,5]
GET Mean (Average)

Operation: op=mean

Parameters:

  • values (required) - Array of numbers

Example:

?op=mean&values=1,2,3,4,5 Result: 3
GET Median

Operation: op=median

Parameters:

  • values (required) - Array of numbers

Example:

?op=median&values=1,2,3,4,5 Result: 3
GET Mode

Operation: op=mode

Parameters:

  • values (required) - Array of numbers

Example:

?op=mode&values=1,2,2,3,4 Result: [2]
GET Variance

Operation: op=variance

Parameters:

  • values (required) - Array of numbers
  • sample (optional) - true for sample variance, false for population (default: true)

Example:

?op=variance&values=1,2,3,4,5&sample=true Result: 2.5
GET Standard Deviation

Operation: op=stddev

Parameters:

  • values (required) - Array of numbers
  • sample (optional) - true for sample, false for population (default: true)

Example:

?op=stddev&values=1,2,3,4,5&sample=true Result: 1.581
GET Sum

Operation: op=sum

Parameters:

  • values (required) - Array of numbers

Example:

?op=sum&values=1,2,3,4,5 Result: 15
GET Product

Operation: op=product

Parameters:

  • values (required) - Array of numbers

Example:

?op=product&values=1,2,3,4,5 Result: 120
GET Minimum

Operation: op=min

Parameters:

  • values (required) - Array of numbers

Example:

?op=min&values=5,2,8,1,9 Result: 1
GET Maximum

Operation: op=max

Parameters:

  • values (required) - Array of numbers

Example:

?op=max&values=5,2,8,1,9 Result: 9
GET Range

Operation: op=range

Parameters:

  • values (required) - Array of numbers

Example:

?op=range&values=5,2,8,1,9 Result: 8

🔬 Advanced Operations

Number Theory

GET Greatest Common Divisor (GCD)

Operation: op=gcd

Parameters:

  • a (required) - First integer
  • b (required) - Second integer

Example:

?op=gcd&a=48&b=18 Result: 6
GET Least Common Multiple (LCM)

Operation: op=lcm

Parameters:

  • a (required) - First integer
  • b (required) - Second integer

Example:

?op=lcm&a=12&b=18 Result: 36
GET Prime Check

Operation: op=isPrime

Parameters:

  • n (required) - Integer to check

Example:

?op=isPrime&n=17 Result: true

Combinatorics

GET Permutation

Operation: op=permutation

Parameters:

  • n (required) - Total items
  • r (required) - Items to arrange

Example:

?op=permutation&n=5&r=3 Result: 60

Formula: P(n,r) = n! / (n-r)!

GET Combination

Operation: op=combination

Parameters:

  • n (required) - Total items
  • r (required) - Items to choose

Example:

?op=combination&n=5&r=3 Result: 10

Formula: C(n,r) = n! / (r! × (n-r)!)

Percentage Operations

GET Calculate Percentage

Operation: op=percentage

Parameters:

  • value (required) - Part value
  • total (required) - Total value

Example:

?op=percentage&value=25&total=200 Result: 12.5
GET Percentage Of

Operation: op=percentageOf

Parameters:

  • percentage (required) - Percentage value
  • total (required) - Total value

Example:

?op=percentageOf&percentage=15&total=200 Result: 30
GET Percentage Increase/Decrease

Operation: op=percentageIncrease

Parameters:

  • original (required) - Original value
  • new (required) - New value

Example:

?op=percentageIncrease&original=100&new=150 Result: 50

Quadratic Equation Solver

GET Solve Quadratic Equation

Operation: op=quadratic

Parameters:

  • a (required) - Coefficient of x²
  • b (required) - Coefficient of x
  • c (required) - Constant term

Example:

?op=quadratic&a=1&b=-5&c=6 Result: { "root1": 3, "root2": 2, "discriminant": 1 }

Formula: ax² + bx + c = 0

Note: If discriminant is negative, roots will be returned as complex numbers with 'real' and 'imaginary' parts.

Conversion Functions

Operation Parameters Description Example
op=degToRad degrees Convert degrees to radians ?op=degToRad°rees=180 → 3.14159
op=radToDeg radians Convert radians to degrees ?op=radToDeg&radians=3.14159 → 180

Random Number Generation

GET Random Float

Operation: op=random

Parameters:

  • min (optional) - Minimum value (default: 0)
  • max (optional) - Maximum value (default: 1)

Example:

?op=random&min=0&max=100 Result: 42.7853 (random)
GET Random Integer

Operation: op=randomInt

Parameters:

  • min (required) - Minimum value
  • max (required) - Maximum value

Example:

?op=randomInt&min=1&max=100 Result: 42 (random)

Constants

GET Get Mathematical Constants

Operation: op=constants

Parameters: None

Example:

?op=constants Result: { "pi": 3.14159265359, "e": 2.71828182846, "goldenRatio": 1.61803398875 }

⚠️ Error Handling

The API returns appropriate error messages for invalid inputs or operations. All errors follow this format:

{ "success": false, "error": "Error message description" }

Common Error Messages

Error Cause Solution
No operation specified Missing 'op' parameter Add ?op=operation_name to request
Unknown operation: [name] Invalid operation name Check operation name spelling
Missing required parameter: [name] Required parameter not provided Add the missing parameter
Division by zero Attempted to divide by 0 Use non-zero divisor
Cannot calculate square root of negative number Negative input for sqrt Use non-negative number
Factorial not defined for negative numbers Negative input for factorial Use non-negative integer
Factorial too large to calculate Input > 170 Use smaller number (≤170)
Logarithm undefined for non-positive numbers Zero or negative input for log Use positive number
Arcsine domain error Value outside [-1, 1] Use value between -1 and 1
Array cannot be empty Empty array for statistics Provide at least one value

HTTP Status Codes

Status Code Meaning When It Occurs
200 OK Successful operation
400 Bad Request Invalid parameters or operation error

💡 Usage Examples

JavaScript / Fetch API

// Simple calculation fetch('https://www.promptbox.cn/api/calculator.php?op=add&a=5&b=3') .then(response => response.json()) .then(data => { console.log(data.result); // 8 }); // Trigonometric function fetch('https://www.promptbox.cn/api/calculator.php?op=sin&angle=90&angleMode=deg') .then(response => response.json()) .then(data => { console.log(data.result); // 1 }); // Statistics fetch('https://www.promptbox.cn/api/calculator.php?op=mean&values=1,2,3,4,5') .then(response => response.json()) .then(data => { console.log(data.result); // 3 }); // Error handling fetch('https://www.promptbox.cn/api/calculator.php?op=divide&a=10&b=0') .then(response => response.json()) .then(data => { if (!data.success) { console.error(data.error); // "Division by zero" } });

Python / Requests

import requests # Basic operation response = requests.get('https://www.promptbox.cn/api/calculator.php', params={ 'op': 'power', 'base': 2, 'exponent': 10 }) result = response.json() print(result['result']) # 1024 # Statistics with array response = requests.get('https://www.promptbox.cn/api/calculator.php', params={ 'op': 'stddev', 'values': '10,20,30,40,50', 'sample': 'true' }) result = response.json() print(result['result']) # Standard deviation # POST request response = requests.post('https://www.promptbox.cn/api/calculator.php', data={ 'op': 'quadratic', 'a': 1, 'b': -5, 'c': 6 }) result = response.json() print(result['result']) # {'root1': 3, 'root2': 2, 'discriminant': 1}

PHP / cURL

<?php // Simple GET request $url = 'https://www.promptbox.cn/api/calculator.php?op=sqrt&n=144'; $response = file_get_contents($url); $data = json_decode($response, true); echo $data['result']; // 12 // cURL POST request $ch = curl_init('https://www.promptbox.cn/api/calculator.php'); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, [ 'op' => 'factorial', 'n' => 5 ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); $data = json_decode($response, true); echo $data['result']; // 120 ?>

jQuery / AJAX

// GET request $.ajax({ url: 'https://www.promptbox.cn/api/calculator.php', method: 'GET', data: { op: 'cos', angle: 60, angleMode: 'deg' }, success: function(response) { console.log(response.result); // 0.5 }, error: function(xhr, status, error) { console.error('Error:', error); } }); // POST request with array $.ajax({ url: 'https://www.promptbox.cn/api/calculator.php', method: 'POST', data: { op: 'median', values: '5,2,8,1,9' }, success: function(response) { console.log(response.result); // 5 } });

cURL Command Line

# GET request curl "https://www.promptbox.cn/api/calculator.php?op=ln&n=2.718281828" # POST request curl -X POST https://www.promptbox.cn/api/calculator.php \ -d "op=gcd" \ -d "a=48" \ -d "b=18" # With JSON response formatting (using jq) curl "https://www.promptbox.cn/api/calculator.php?op=constants" | jq # Statistics example curl "https://www.promptbox.cn/api/calculator.php?op=mean&values=10,20,30,40,50"

❓ Help & Support

List All Operations

To get a complete list of all available operations grouped by category:

GET https://www.promptbox.cn/api/calculator.php?op=help

This returns a JSON object with all operations organized by category:

{ "success": true, "operation": "help", "result": { "basic": ["add", "subtract", "multiply", ...], "trigonometry": ["sin", "cos", "tan", ...], "statistics": ["mean", "median", "mode", ...], ... } }

Quick Reference

Basic Math

add, subtract, multiply, divide, modulo, power, sqrt, abs, factorial

Trigonometry

sin , cos, tan, asin, acos, atan, atan2, sinh, cosh, tanh

Logarithmic

ln, log, log10, log2, exp

Statistics

mean, median, mode, variance, stddev, sum, product, min, max, range

Number Theory

gcd, lcm, isPrime, factorial

Combinatorics

permutation, combination

Percentage

percentage, percentageOf, percentageIncrease

Other

round, floor, ceil, quadratic, random, randomInt, constants

Tips & Best Practices

  1. URL Encoding: Always URL-encode parameters, especially when passing negative numbers or special characters.
  2. Precision: Floating-point calculations may have minor precision errors. Use rounding functions when necessary.
  3. Array Format: Arrays can be passed as comma-separated values or JSON arrays. Both formats are supported.
  4. Angle Mode: Remember to specify angleMode=deg for trigonometric functions if working in degrees.
  5. Error Handling: Always check the success field in responses before using results.
  6. Rate Limiting: Be respectful with API usage. Consider caching results for repeated calculations.
  7. CORS: The API supports cross-origin requests, so it can be called from browser JavaScript.
Performance Tip: For multiple calculations, consider making separate requests rather than combining operations, as the API is optimized for single operations.

📚 Complete Operation Reference

All Available Operations

Category Operation Required Parameters Optional Parameters
Basic add a, b -
subtract a, b -
multiply a, b -
divide a, b -
modulo a, b -
power base, exponent -
sqrt n -
nthRoot n, root -
abs n -
factorial n -
Trigonometry sin angle angleMode
cos angle angleMode
tan angle angleMode
asin value angleMode
acos value angleMode
atan value angleMode
atan2 y, x angleMode
Hyperbolic sinh x -
cosh x -
tanh x -
asinh x -
acosh x -
atanh x -
Logarithmic ln n -
log n base
log10 n -
log2 n -
exp n -
Rounding round n precision
floor n -
ceil n -
Number Theory gcd a, b -
lcm a, b -
isPrime n -
Combinatorics permutation n, r -
combination n, r -
Statistics mean values -
median values -
mode values -
variance values sample
stddev values sample
sum values -
product values -
min values -
max values -
range values -
Conversion degToRad degrees -
radToDeg radians -
Percentage percentage value, total -
percentageOf percentage, total -
percentageIncrease original, new -
Equation quadratic a, b, c -
Random random - min, max
randomInt min, max -
Utility constants - -
Help help - -

🤔 Frequently Asked Questions

Q: Is there a rate limit on API requests?

A: Currently, there are no strict rate limits, but please use the API responsibly. Excessive usage may result in temporary restrictions.

Q: Can I use this API in production applications?

A: Yes, the API is stable and can be used in production. However, consider implementing proper error handling and caching for better performance.

Q: What is the maximum precision for calculations?

A: The API uses PHP's floating-point arithmetic, which provides approximately 15 decimal digits of precision. For higher precision requirements, consider using specialized libraries.

Q: How do I pass negative numbers in the URL?

A: URL-encode negative numbers or use POST requests. Example: ?op=add&a=-5&b=3 or encode as ?op=add&a=%2D5&b=3

Q: Can I batch multiple operations in one request?

A: No, each request performs a single operation. Make multiple requests for multiple calculations.

Q: Is HTTPS supported?

A: Yes, the API is accessible via HTTPS at https://www.promptbox.cn/api/calculator.php

Q: What happens if I pass invalid parameters?

A: The API will return a JSON error response with "success": false and an error message describing the issue.

Q: Are there client libraries available?

A: Currently, no official client libraries exist, but the API is simple enough to use directly with HTTP clients in any programming language.

Q: Can I perform matrix operations?

A: No, the current version does not support matrix operations. It focuses on scalar calculations and basic statistics.

Q: How accurate are trigonometric functions?

A: Trigonometric functions use PHP's built-in math functions, which are highly accurate for most applications. Minor floating-point errors may occur in edge cases.

📝 Version Information

Current Version: 1.0

Features

  • ✅ Complete basic arithmetic operations
  • ✅ Comprehensive trigonometric functions (regular and hyperbolic)
  • ✅ Logarithmic and exponential functions
  • ✅ Statistical operations for data analysis
  • ✅ Number theory functions (GCD, LCM, prime checking)
  • ✅ Combinatorics (permutations and combinations)
  • ✅ Percentage calculations
  • ✅ Quadratic equation solver
  • ✅ Random number generation
  • ✅ Angle mode support (degrees/radians)
  • ✅ Comprehensive error handling
  • ✅ CORS support for browser requests
  • ✅ JSON response format
  • ✅ GET and POST method support

Planned Features

  • 🔜 Matrix operations
  • 🔜 Complex number arithmetic
  • 🔜 Polynomial operations
  • 🔜 Calculus functions (derivatives, integrals)
  • 🔜 Unit conversions
  • 🔜 Financial calculations
  • 🔜 Date/time calculations