← Back to Bash Course | Chapter 4: Loops | Lesson 13 of 14

Math के Functions

Bash का अपना math सिर्फ कुछ buttons वाले एक basic calculator जैसा है। Square roots जैसी fancier tricks के लिए, यह help के लिए एक बड़े calculator को call करता है।

In this page:

  1. Math Functions
Syntax
bash
result=$(( base ** exponent ))
result=$(echo "function(number)" | bc -l)

Math Functions

Bash में खुद $(( )) में integer exponentiation के लिए ** के अलावा square root या power जैसा कोई built-in function नहीं है।

ज़्यादा advanced किसी भी चीज़ के लिए, scripts bc -l (जो sqrt(), sine के लिए s(), आदि support करता है) या awk को shell out करती हैं। यह जानना कि कब एक external tool को delegate करना है, effective Bash लिखने का हिस्सा है।

Note: $(( 2 ** 10 )) बिना bc की ज़रूरत के directly integer powers compute करता है।

उदाहरण: Math Functions

bash
#!/bin/bash
echo "2^10 = $((2 ** 10))"

sqrt_result=$(echo "sqrt(16)" | bc -l)
echo "sqrt(16) = $sqrt_result"
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. Bash से sqrt() या sin() देने की उम्मीद करना, जब integer arithmetic में कोई नहीं है; bc -l उपयोग करें।
  2. यह भूल जाना कि RANDOM 0 से 32767 तक एक integer देता है।
  3. $(( 7 / 2 )) से round होने की उम्मीद करना, जब यह truncate करता है।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.