Daftar Referensi Python

Modul math berisi fungsi matematika bawaan Python: akar, pembulatan ke atas/bawah, faktorial, sampai konstanta seperti pi. Sudah termasuk saat Python dipasang — cukup import math, tanpa pip install.

Sintaks

import math

math.sqrt(144)  # panggil dengan awalan math.

Fungsi dan Konstanta yang Sering Dipakai

Fungsi Untuk apa Contoh
math.sqrt(x) akar kuadrat math.sqrt(144) = 12.0
math.ceil(x) bulatkan ke atas math.ceil(3.2) = 4
math.floor(x) bulatkan ke bawah math.floor(3.9) = 3
math.pow(x, y) pangkat (hasil float) math.pow(2, 10) = 1024.0
math.fabs(x) nilai mutlak (float) math.fabs(-7.5) = 7.5
math.factorial(n) faktorial math.factorial(5) = 120
math.gcd(a, b) FPB dua bilangan math.gcd(12, 18) = 6
math.pi konstanta pi 3.14159…
math.e konstanta Euler 2.71828…

Contoh

import math

print(math.sqrt(144))
print(math.ceil(3.2))
print(math.floor(3.9))

Coba di IDE

Output:

12.0
4
3

Contoh Lainnya

Faktorial dan FPB

import math

print(math.factorial(6))
print(math.gcd(12, 18))

Coba di IDE

Output:

720
6

Konstanta pi: luas lingkaran

import math

jari = 7
luas = math.pi * jari ** 2
print(round(luas, 2))

Coba di IDE

Output:

153.94

Pangkat dan nilai mutlak

import math

print(math.pow(2, 10))
print(math.fabs(-7.5))

Coba di IDE

Output:

1024.0
7.5

Kesalahan Umum

  • Lupa import mathNameError: name 'math' is not defined.
  • Lupa awalan: sqrt(9) setelah import mathNameError. Tulis math.sqrt(9), atau import spesifik: from math import sqrt.
  • math.sqrt(-1)ValueError: math domain error.
  • math.ceil/math.floor berbeda dari round() — ceil selalu ke atas, floor selalu ke bawah, round ke yang terdekat.

Pelajari Lebih Lanjut