math Package का उपयोग
math.Sqrt(x)
math.Pow(x, y)
math.Max(a, b)
math.Floor(x)
Square Roots and Powers
math.Sqrt एक square root compute करता है, और math.Pow किसी base को एक exponent तक उठाता है -- दोनों float64 पर operate करते हैं और इसे return करते हैं, इसलिए integer inputs को explicit conversion चाहिए।
उदाहरण: Square Roots and Powers
// Every Go file belongs to a package; main builds an executable
package main
// Import the packages this program uses
import (
"fmt"
"math"
)
// main is where the program starts running
func main() {
// Print the values followed by a newline
fmt.Println(math.Sqrt(16))
// Print the values followed by a newline
fmt.Println(math.Pow(2, 10))
}
Login to try C/C++/Java/PHP code in the editor
Absolute Value and Comparisons
math.Abs किसी value का non-negative magnitude return करता है, जबकि math.Max और math.Min बिल्कुल दो float64 arguments में से बड़ा या छोटा return करते हैं।
उदाहरण: Absolute Value and Comparisons
// Every Go file belongs to a package; main builds an executable
package main
// Import the packages this program uses
import (
"fmt"
"math"
)
// main is where the program starts running
func main() {
// Print the values followed by a newline
fmt.Println(math.Abs(-7.5))
// Print the values followed by a newline
fmt.Println(math.Max(3.2, 8.1))
fmt.Println(math.Min(3.2, 8.1))
}
Login to try C/C++/Java/PHP code in the editor
Rounding Numbers
math.Round सबसे नज़दीकी whole number तक round करता है, math.Floor हमेशा नीचे round करता है, और math.Ceil हमेशा ऊपर round करता है -- हर एक उस whole number को represent करता एक float64 return करते हुए।
उदाहरण: Rounding Numbers
// Every Go file belongs to a package; main builds an executable
package main
// Import the packages this program uses
import (
"fmt"
"math"
)
// main is where the program starts running
func main() {
// Short declaration: create n and infer the type
n := 4.6
// Print the values followed by a newline
fmt.Println(math.Round(n))
// Print the values followed by a newline
fmt.Println(math.Floor(n))
fmt.Println(math.Ceil(n))
}
Login to try C/C++/Java/PHP code in the editor
- यह भूल जाना कि math functions float64 पर काम करते हैं, किसी int से शुरू करते समय explicit conversion मांगते हुए।
- यह मान लेना कि math.Max/Min सीधे slices पर काम करते हैं -- वे एक समय में सिर्फ दो float64 values compare करते हैं।
- math.IsNaN या math.IsInf न जांचना जब कोई computation (जैसे zero से float के रूप में divide करना) एक non-numeric result produce कर सकता है।
- math package float64 values के साथ काम करता है, इसलिए ints को पहले explicitly convert करना चाहिए।
- math.Sqrt, math.Pow, और math.Abs आम numeric operations handle करते हैं।
- math.Max और math.Min एक समय में बिल्कुल दो float64 values compare करते हैं।
- math.Round, Floor, और Ceil नियंत्रित करते हैं कि किसी float को whole number में कैसे round किया जाए।
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: