Python math मॉड्यूल
In this page:
import math
math.function_name(number) # e.g. math.sqrt(number)
math.pi
Numbers को Round करना
math मॉड्यूल तेज़ numeric computation के लिए C standard library के math functions को wrap करता है।
math.floor() हमेशा value को negative infinity की तरफ नीचे round करता है और math.ceil() हमेशा positive infinity की तरफ ऊपर, जो Python के built-in round() से अलग है, जो banker's rounding इस्तेमाल करके nearest value तक round करता है।
उदाहरण: Rounding Numbers
import math
print(math.floor(4.7)) # rounds down toward negative infinity
print(math.ceil(4.2)) # rounds up toward positive infinity
print(round(4.5)) # built-in round(), uses banker's rounding
Powers और Square Roots
math.sqrt() square root निकालता है और negative inputs के लिए ValueError raise करता है, क्योंकि यह सिर्फ real numbers के साथ काम करता है (complex results चाहिए तो अलग cmath मॉड्यूल इस्तेमाल करें)।
math.pow() किसी number को दी गई power तक raise करता है और हमेशा एक float लौटाता है, जबकि ** operator दोनों operands integer होने पर integer result बरकरार रखता है।
उदाहरण: Powers and Square Roots
import math
print(math.sqrt(16)) # square root
print(math.pow(2, 3)) # always returns a float, unlike **
Trigonometric Functions
math.sin(), math.cos(), और math.tan() सभी अपना input angle degrees में नहीं बल्कि radians में expect करते हैं -- यह शुरुआती लोगों के लिए सूक्ष्म रूप से गलत output का एक बहुत आम कारण है।
किसी degree value को किसी भी trigonometric function में भेजने से पहले उसे radians में बदलने के लिए math.radians() इस्तेमाल करें।
उदाहरण: Trigonometric Functions
import math
angle = math.radians(90) # convert degrees to radians first
print(math.sin(angle)) # trig functions expect radians, not degrees
Logarithmic Functions
math.log() default रूप से natural logarithm (base e) निकालता है, लेकिन किसी दूसरे base में logarithm निकालने के लिए एक वैकल्पिक दूसरा argument भी स्वीकार करता है।
math.log10() और math.log2() सबसे ज़्यादा इस्तेमाल होने वाले दो bases के लिए अलग, ज़्यादा precise shortcuts हैं।
उदाहरण: Logarithmic Functions
import math
print(math.log(math.e)) # natural log, base e
print(math.log10(1000)) # base 10
print(math.log2(8)) # base 2
Mathematical Constants
math.pi, math.tau (2π), और math.e पूरी floating-point precision के साथ पहले से calculate किए गए हैं, जिससे आपको 3.14159 जैसा कोई approximation hardcode नहीं करना पड़ता जो scientific या engineering calculations में छोटी मगर असली errors ला सकता था।
उदाहरण: Mathematical Constants
import math
print(math.pi) # precomputed to full floating-point precision
print(math.tau) # 2 * pi
print(math.e)
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: