The Python Square Root Function – Real Python (2024)

Table of Contents

  • Square Roots in Mathematics
  • The Python Square Root Function
    • The Square Root of a Positive Number
    • The Square Root of Zero
    • The Square Root of Negative Numbers
  • Square Roots in the Real World
  • Conclusion

Remove ads

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: The Square Root Function in Python

Are you trying to solve a quadratic equation? Maybe you need to calculate the length of one side of a right triangle. For these types of equations and more, the Python square root function, sqrt(), can help you quickly and accurately calculate your solutions.

By the end of this article, you’ll learn:

  • What a square root is
  • How to use the Python square root function, sqrt()
  • When sqrt() can be useful in the real world

Let’s dive in!

Python Pit Stop: This tutorial is a quick and practical way to find the info you need, so you’ll be back to your project in no time!

Free Bonus: Click here to get our free Python Cheat Sheet that shows you the basics of Python 3, like working with data types, dictionaries, lists, and Python functions.

Square Roots in Mathematics

In algebra, a square, x, is the result of a number, n, multiplied by itself: x = n²

You can calculate squares using Python:

Python

>>> n = 5>>> x = n ** 2>>> x25

The Python ** operator is used for calculating the power of a number. In this case, 5 squared, or 5 to the power of 2, is 25.

The square root, then, is the number n, which when multiplied by itself yields the square, x.

In this example, n, the square root, is 5.

25 is an example of a perfect square. Perfect squares are the squares of integer values:

You might have memorized some of these perfect squares when you learned your multiplication tables in an elementary algebra class.

If you’re given a small perfect square, it may be straightforward enough to calculate or memorize its square root. But for most other squares, this calculation can get a bit more tedious. Often, an estimation is good enough when you don’t have a calculator.

Fortunately, as a Python developer, you do have a calculator, namely the Python interpreter!

Remove ads

The Python Square Root Function

Python’s math module, in the standard library, can help you work on math-related problems in code. It contains many useful functions, such as remainder() and factorial(). It also includes the Python square root function, sqrt().

You’ll begin by importing math:

Python

>>> import math

That’s all it takes! You can now use math.sqrt() to calculate square roots.

sqrt() has a straightforward interface.

It takes one parameter, x, which (as you saw before) stands for the square for which you are trying to calculate the square root. In the example from earlier, this would be 25.

The return value of sqrt() is the square root of x, as a floating point number. In the example, this would be 5.0.

Let’s take a look at some examples of how to (and how not to) use sqrt().

The Square Root of a Positive Number

One type of argument you can pass to sqrt() is a positive number. This includes both int and float types.

For example, you can solve for the square root of 49 using sqrt():

The return value is 7.0 (the square root of 49) as a floating point number.

Along with integers, you can also pass float values:

Python

>>> math.sqrt(70.5)8.396427811873332

You can verify the accuracy of this square root by calculating its inverse:

Python

>>> 8.396427811873332 ** 270.5

The Square Root of Zero

Even 0 is a valid square to pass to the Python square root function:

Python

>>> math.sqrt(0)0.0

While you probably won’t need to calculate the square root of zero often, you may be passing a variable to sqrt() whose value you don’t actually know. So, it’s good to know that it can handle zero in those cases.

Remove ads

The Square Root of Negative Numbers

The square of any real number cannot be negative. This is because a negative product is only possible if one factor is positive and the other is negative. A square, by definition, is the product of a number and itself, so it’s impossible to have a negative real square:

Python

>>> math.sqrt(-25)Traceback (most recent call last): File "<stdin>", line 1, in <module>ValueError: math domain error

If you attempt to pass a negative number to sqrt(), then you’ll get a ValueError because negative numbers are not in the domain of possible real squares. Instead, the square root of a negative number would need to be complex, which is outside the scope of the Python square root function.

Square Roots in the Real World

To see a real-world application of the Python square root function, let’s turn to the sport of tennis.

Imagine that Rafael Nadal, one of the fastest players in the world, has just hit a forehand from the back corner, where the baseline meets the sideline of the tennis court:

Now, assume his opponent has countered with a drop shot (one that would place the ball short with little forward momentum) to the opposite corner, where the other sideline meets the net:

How far must Nadal run to reach the ball?

You can determine from regulation tennis court dimensions that the baseline is 27 feet long, and the sideline (on one side of the net) is 39 feet long. So, essentially, this boils down to solving for the hypotenuse of a right triangle:

Using a valuable equation from geometry, the Pythagorean theorem, we know that a² + b² = c², where a and b are the legs of the right triangle and c is the hypotenuse.

Therefore, we can calculate the distance Nadal must run by rearranging the equation to solve for c:

You can solve this equation using the Python square root function:

Python

>>> a = 27>>> b = 39>>> math.sqrt(a ** 2 + b ** 2)47.43416490252569

So, Nadal must run about 47.4 feet (14.5 meters) in order to reach the ball and save the point.

Conclusion

Congratulations! You now know all about the Python square root function.

You’ve covered:

  • A brief introduction to square roots
  • The ins and outs of the Python square root function, sqrt()
  • A practical application of sqrt() using a real-world example

Knowing how to use sqrt() is only half the battle. Understanding when to use it is the other. Now, you know both, so go and apply your newfound mastery of the Python square root function!

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: The Square Root Function in Python

The Python Square Root Function – Real Python (2024)
Top Articles
Grab this ice cream maker while it's discounted in Walmart's sale | Digital Trends
Grab the TikTok-favorite Ninja Creami ice cream-maker at Walmart for $30 off
Incredibox Deluxe
Urbfsdreamgirl
Air Chat En Espanol
Restored Republic June 6 2023
Fresenius Medical Care to launch 5008 dialysis machine: improved patients` quality of life and efficient use of resources
104 Whiley Road Lancaster Ohio
Bg3 Fake Portrait Of A Noble Before His Death
The 8 Best Santa Ynez Wineries to Visit in 2023
Aita For Helping My Girlfriend Get Over Her Trauma
Tammi Light Obituary
Mychart.solutionhealth.org/Mychartprd/Billing/Summary
Lynchburg Arrest.org
Great Clips Coupons → 20% Off | Sep 2024
PNC Bank Review 2024
Mobile Maher Terminal
Shore Lodge Webcam
Praxis für Psychotherapie und Coaching Rhein-Neckar
Labcorp Locations Near Me
Weird Al.setlist
Redgifs.comn
Beetrose 'Planten un Blomen' - Rosa 'Planten un Blomen' ADR-Rose
Sloansmoans Many
3850 Colonial Blvd Suite 100 Fort Myers Fl 33966
Los Garroberros Menu
Arsenal news LIVE: Latest updates from the Emirates
Exploring The Craigslist Washington DC Marketplace - A Complete Overview
Www.cvs/Otchs/Simply
Royal Carting Holidays 2022
Hose Woe Crossword Clue
Skyward Weatherford Isd Login
This Is The Right Order To Watch Every X-Men Movie - Looper
Today's Wordle Mashable
JetBlue, Spirit end $3.8 billion merger agreement after losing antitrust suit
Vogler Funeral Home At Forsyth Memorial Park
Jetnet Retirees Aa
Mygxo Gxo Com Employee Login
Metalico Sharon Pa
99 Cents Food Handler
Trap Candy Strain Leafly
Concord Mills Mall Store Directory
L898 Pill Blue Capsule
Luchtvaart- en Ruimtevaarttechniek - Technische Universiteit Delft - Studiekeuze123 - Studiekeuze123
Jason Brewer Leaving Fox 25
Sloansmoans Many
Smithfield Okta Login
Tighe Hamilton Hudson Ma Obituary
Black Panther Pitbull Puppy For Sale
Dragith Nurn Rs3
Wiley Rein Vault
8X10 Meters To Square Meters
Latest Posts
Article information

Author: Duane Harber

Last Updated:

Views: 6567

Rating: 4 / 5 (71 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Duane Harber

Birthday: 1999-10-17

Address: Apt. 404 9899 Magnolia Roads, Port Royceville, ID 78186

Phone: +186911129794335

Job: Human Hospitality Planner

Hobby: Listening to music, Orienteering, Knapping, Dance, Mountain biking, Fishing, Pottery

Introduction: My name is Duane Harber, I am a modern, clever, handsome, fair, agreeable, inexpensive, beautiful person who loves writing and wants to share my knowledge and understanding with you.