math Module Examples


math Module Examples

This document introduces common mathematical functions in math module. API reference: doc/pikapython.com/_sources/API_math.md.txt.

Module Introduction

math provides rounding, exponential logarithm, power and square root, trigonometric functions, etc. Built-in example:

#!pika
import math
math.sqrt(2)
math.sin(0)
math.floor(1.6)
math.ceil(1.2)
#!pika

API Overview (excerpt)

Function Description Example
ceil(x) Round up math.ceil(1.2) → 2
floor(x) Round down math.floor(1.8) → 1
fabs(x) Absolute value math.fabs(-1.5) → 1.5
fmod(x,y) Float modulo math.fmod(5.5, 2)
sqrt(x) Square root math.sqrt(2)
pow(x,y) Power math.pow(2, 3) → 8.0
sin/cos/tan Trigonometric functions math.sin(0) → 0.0
asin/acos/atan Inverse trigonometric functions math.asin(0) → 0.0
exp(x), log(x), log2(x), log10(x) Exponential and logarithm Subject to actual API

Example Code

#!pika
import math

# Rounding and absolute value
assert math.ceil(1.2) == 2
assert math.floor(1.8) == 1
assert math.fabs(-3.5) == 3.5

# Power and square root
assert math.pow(2, 3) == 8.0
assert math.sqrt(4) == 2.0

# Trigonometric functions (radians)
assert math.sin(0) == 0.0
assert math.cos(0) == 1.0
assert math.tan(0) == 0.0

# Common constants (if implementation provides)
# pi = math.pi
# e  = math.e

print('PASS')
#!pika

Note: Specific provided functions and constants follow device’s math module in firmware, unimplemented calls will error.

Notes

  • Trigonometric function parameters are radians, degrees need to multiply by math.pi/180 (if pi provided).
  • Embedded implementations may only include partial functions, check device or PikaPython documentation before use.