Rootpy 1.0.1

Rootpy 1.0.1

PyPI version
Conda-Forge
Python 3.7‒3.11
BSD-3 Clause License
Continuous integration tests

Scikit-HEP
NSF-1836650
DOI 10.5281/zenodo.4340632
Documentation
Gitter

Uproot is a library for reading and writing ROOT files in pure Python and NumPy.

Rootpy 1.0.1

In this tutorial, you’ll learn how to calculate use Python to calculate the square root of a number, using the .sqrt() function. You’ll learn how to do this with, and without, the popular math library that comes built into Python. You’ll also learn what a square root is, what limitations there are of square roots, and how to calculate the integer square root using the math.isqrt() function.

The Quick Answer: Use math.sqrt() to Calculate a Python Square Root

Square Root Quick Answer
Use the math library to calculate a square root with Python!

Let’s see what you’ll learn in this post!

So you want the script to run as root, even without sudo? For that you would need to set the setuid bit on the script with sudo chmod u+s program. However, most Unix distributions allow this only for binaries, and not for scripts, for security reasons. In general it’s really not a good idea to do that.

If you want to run this script as root, you will have to run as sudo. Or, you have to create a binary that runs your script, so that you can set the setuid bit on this binary wrapper. This related question explains more.

if not os.geteuid() == 0: sys.exit("\nOnly root can run this script\n")
command -v python
sudo command -v python

It shouldn’t be necessary to make the owner of the script root, and to run it with sudo. You just need to configure python and PYTHONPATH correctly.

Is it possible to ask for a root pw without storing in in my script memory and to run some of os.* commands as root?

  1. scans some folders and files to check if it can do the job
  2. makes some changes in /etc/…
  3. creates a folder and files that should be owned by the user who ran the script

Tanks 2 all for suggestions

The solution so far is:

# do all in sudo
os.chown(folder, int(os.getenv('SUDO_UID')), int(os.getenv('SUDO_GID')))

thanks to gnibbler for hint.

asked Oct 28, 2009 at 9:40

culebrón's user avatar

20 gold badges72 silver badges110 bronze badges

Maybe you can put (2) in a separate script, say script2.py, and in the main script you call sudo script2.py with a popen ?

This way only (2) will be executed as root.

answered Oct 28, 2009 at 10:02

jdb's user avatar

2 silver badges3 bronze badges

run_part_1()
subprocess.call(['sudo', sys.executable, 'part2.py'])
run_part_3()
run_part_2()

answered Oct 28, 2009 at 10:29

nosklo's user avatar

56 gold badges293 silver badges297 bronze badges

You should execute your script as root and do the proper changes to permissions for (3) using os.chmod and os.chown.

One final note: You don’t have to worry about the permissions of symlinks. They have the permissions of what they point to.

answered Oct 28, 2009 at 13:43

Craig Younkins's user avatar

Craig Younkins

2 gold badges11 silver badges18 bronze badges

os.chown, (some_path, int(os.getenv('SUDO_UID')), int(os.getenv('SUDO_GID')))

Splitting the code in 3 files could be a solution, but the code is already mixed, so that’s not suitable.

Community's user avatar

answered Nov 6, 2009 at 7:40

culebrón's user avatar

20 gold badges72 silver badges110 bronze badges

Are you trying to solve a quadratic equation? Maybe you need to calculate the length of one side of a right triangle. You can use the math module’s sqrt() method for determining the square root of a number. This course covers the use of math.sqrt() as well as related methods.

In this course, you’ll learn:

  • About square roots and related mathematical operations
  • How to use the Python square root function, sqrt()
  • Where sqrt() can be useful in real-world examples

00:00

Welcome to Square Root in Python. My name is Chris, and I will be your guide.

00:06

In this course, you will learn what are square roots, powers, and n-th roots, how to get a square root in Python, how square roots are calculated, and using square roots in practice.

00:20

A quick note on versions: All code in this course was tested with Python 3.9. Square root has been around since the beginning, so most things will work in most versions, and I’ll do my best to point out differences as I go along.

00:34

A square is any number multiplied by itself. A square root is a number that when multiplied by itself gives the square. 5 squared is 25, so the square root of 25 is 5.

00:48

The knowledge of square roots has been around for thousands of years. There are Babylonian clay tablets dating from 1800 BCE that reference this concept.

00:57

Python provides a method for calculating square roots as part of the math library. Next up, I’ll show you some square roots and how to find them in code.

Содержание
  1. Newton’s method
  2. Square Roots in Mathematics
  3. The Python Square Root Function
  4. The Square Root of a Positive Number
  5. The Square Root of Zero
  6. The Square Root of Negative Numbers
  7. Square Roots in the Real World
  8. Conclusion
  9. 1) What is python?
  10. 2) Python vs c++
  11. 3) Running the python interpreter
  12. 4) Basic Syntax
  13. 5) Built-in Types and simple functions
  14. 6) Containers
  15. Lists
  16. More on strings
  17. Dictionary
  18. 7) Loops and conditionals
  19. «if» conditional
  20. Loops
  21. 8) File I/O
  22. 9) Writing functions
  23. 10) Keywords
  24. 11) Modules and passing command line arguments to python
  25. The sys module
  26. 12) Extending python with additional modules and running newer python versions
  27. Running newer versions of python in your virtualenv
  28. Running python3 virtualenvs
  29. Multiple simultaneous environments (advanced)
  30. 13) pyROOT — for PP students only
  31. Filling an ntuple
  32. Garbage collection (specific to ROOT but not specific to pyROOT)
  33. 15) Optimization tricks
  34. Common cause of python slowdowns
  35. 16) Ipython notebooks
  36. jupyter
  37. EDIT
  38. Overcoming the issues and limits of this method/implementation:
  39. Fractional exponent
  40. Project description
  41. Binary search
  42. Python Integer Square Root
  43. Acknowledgements
  44. Installation for developers
  45. Installation
  46. ✔ Output 💡 CLICK BELOW & SEE ✔
  47. Python Square Root Using Exponentiation
  48. NumPy
  49. Negative
  50. What is a Square Root?
  51. Square Root Limitations – Negative Numbers and Zero
  52. Calculate the Square Root of Zero Using Python
  53. Calculating the Square Root of Negative Numbers with Python
  54. SymPy
  55. Edge cases
  56. Negative and complex
  57. Precision
  58. Other types
  59. Download files
  60. Source Distribution
  61. Python Square Root Using math. sqrt
  62. Edit 2, on other answers
  63. Arbitrary precision square root
  64. Test
  65. Output
  66. Math. sqrt()
  67. Find square-root of a number
  68. Getting help
  69. Dependencies
  70. Conclusion

Newton’s method

Most simple and accurate way to compute square root is Newton’s method.

You have a number which you want to compute its square root (num) and you have a guess of its square root (estimate). Estimate can be any number bigger than 0, but a number that makes sense shortens the recursive call depth significantly.

new_estimate = (estimate + num/estimate) / 2

This line computes a more accurate estimate with those 2 parameters. You can pass new_estimate value to the function and compute another new_estimate which is more accurate than the previous one or you can make a recursive function definition like this.

def newtons_method(num, estimate): # Computing a new_estimate new_estimate = (estimate + num/estimate) / 2 print(new_estimate) # Base Case: Comparing our estimate with built-in functions value if new_estimate == math.sqrt(num): return True else: return newtons_method(num, new_estimate)

For example we need to find 30’s square root. We know that the result is between 5 and 6.

newtons_method(30,5)

number is 30 and estimate is 5. The result from each recursive calls are:

5.5
5.477272727272727
5.4772255752546215
5.477225575051661

The last result is the most accurate computation of the square root of number. It is the same value as the built-in function math.sqrt().


This answer was originally posted by gunesevitan, but is now deleted.

Python’s fractions module and its class, Fraction, implement arithmetic with rational numbers. The Fraction class doesn’t implement a square root operation, because most square roots are irrational numbers. However, it can be used to approximate a square root with arbitrary accuracy, because a Fraction‘s numerator and denominator are arbitrary-precision integers.

from fractions import Fraction
def sqrt(x, n): x = x if isinstance(x, Fraction) else Fraction(x) upper = x + 1 for i in range(0, n): upper = (upper + x/upper) / 2 lower = x / upper if lower > upper: raise ValueError("Sanity check failed") return (lower, upper)

See the reference below for details on this operation’s implementation. It also shows how to implement other operations with upper and lower bounds (although there is apparently at least one error with the log operation there).

  • Daumas, M., Lester, D., Muñoz, C., «Verified Real Number Calculations: A Library for Interval Arithmetic», arXiv:0708.3721 [cs.MS], 2007.

Alternatively, using Python’s math.isqrt, we can calculate a square root to arbitrary precision:

  • Square root of i within 1/2n of the correct value, where i is an integer:Fraction(math.isqrt(i * 2**(n*2)), 2**n).
  • Square root of i within 1/10n of the correct value, where i is an integer:Fraction(math.isqrt(i * 10**(n*2)), 10**n).
  • Square root of x within 1/2n of the correct value, where x is a multiple of 1/2n:Fraction(math.isqrt(x * 2**(n)), 2**n).
  • Square root of x within 1/10n of the correct value, where x is a multiple of 1/10n:Fraction(math.isqrt(x * 10**(n)), 10**n).

In the foregoing, i or x must be 0 or greater.

answered Jan 21, 2022 at 19:45

Peter O.'s user avatar

Peter O.

14 gold badges82 silver badges95 bronze badges

00:00

In the previous lesson, I gave an overview of the course. In this lesson, I’ll introduce you to square roots in Python. A square is a number that is multiplied by itself.

00:11

There are many ways of expressing this in math and programming. The big cross here indicates multiplication. In most programming languages, the star (*) is used for the same thing. In algebra, the superscript of 2 means to square the value.

00:27

Some programming languages use the caret symbol (^), or Shift + 6 on a U.S. keyboard, to denote exponents. An exponent, or power of 2, is the same as squaring. In Python, double star (**) is the power operator. **2 is the same as square.

00:46

A square root is the number that when squared gives you the question, “If y is equal to x squared, given y, what would x be?” This is also noted as the square root of y. The little check mark here means to take the square root of what is under it. This symbol, the check mark, is called the radical sign, the radical symbol, the root symbol, the radix, or the surd. Here’s an example.

01:14

5 times 5 is 25, so the square root of 25 is 5.

01:22

Let me start by using the power operator to square the number 3. 3 times 3 is 9, all good. Let me do it once more with 5. 5 squared is 25. Now to get the square root, I need to get the function that does this from the math library.

01:45

The square root of 25 is 5.0. 6 squared is 36, so the square root of 36 is 6.0. So far, I’ve only used integers and what are called perfect squares.

01:59

When you square an integer, the result is a perfect square. When you square root a perfect square, you get back that integer. If you square root a number that isn’t a perfect square, you’ll get an irrational number. In Python, these are represented by floats.

02:16

Seeing as I’ve done sqrt() for 25 and 36, you could guess that the square root of 30 is going to be somewhere between 5.0 and 6.0. Let’s see that. And there you go!

02:28

5.47 et cetera. You can see how well this worked by storing it and then squaring the result. Back to 30.0. That worked out well.

02:44

The square root of 0 is 0.0. If you think about it for a moment, that makes sense. 0 times 0 is 0, so the thing you multiply by itself to get 0 is 0. It feels kind of zen.

02:56

You’re not likely to need this directly, but if you’re doing math on a variable and it happens to contain 0, then you know what result to expect. What about negatives?

03:07

Python doesn’t allow this. The square root of a negative number is what’s called a complex number. Python has a method for dealing with complex numbers, but you have to explicitly request that it does so. As I’m just using the vanilla sqrt() here I get a ValueError instead.

03:28

In addition to the sqrt() function, Python 3.8 introduced the isqrt() function in the math module. Now that I’ve imported it, let me run it on 25.

03:39

No problem here. Still in perfect square land. Same thing with 36. And using it on 30 might give you a guess as to what the “i” part in isqrt() stands for. This returns the floor of the square root, giving the integer result.

04:01

In addition to squares, you can also cube something. That’s a number multiplied by itself and then by itself again. Same notations as before, but this time with a 3 instead of a 2.

04:13

The generalization of this is called the power of a number. x to the n-th power is x times x times x, n times. Working that backwards, and you get the n-th root. If y is x to the n, then what is x? To indicate that a root is an n-th root, the n value gets tagged into the front of that root symbol.

04:38

Here’s an example. 4 cubed is 64, so the third root, or cube root, of 64 is 4.

04:50

Python does not have an n-th root function, but that isn’t a problem because of this neat little math trick. The n-th root of something is the same as the value to the power of 1 over n. For instance, the cube root of y is equivalent to y to the power of one third, or 1 over 3. Let’s go back to the REPL and use this.

05:14

Repeating the previous example in the REPL, 4 cubed is 64. You can also use the built-in pow() (power) function to achieve the same thing.

05:25

Or you can use the pow() function from the math module.

05:33

Notice the difference. The one in the math module always returns a float. Now let’s use that fraction trick.

05:42

25 to the power of 1 over 2—that’s a half—is 5. See? Square root! Notice that I wrote 1. inside of the exponent. That is to force Python to treat that number as a float.

05:57

Now let’s use the fractional power to cube root 64.

06:04

And that’s pretty close, but not quite right. This has nothing to do with the formula for the cute root. It has to do with how float numbers are stored in a computer.

06:13

You’ll find a lot of float numbers do weird things when division and fractions are involved. You’ll get little pieces missing. You have to be particularly careful with this when doing a lot of math, as the errors can compound over multiple uses. A little error at the beginning fed into another formula can make you a fair ways off at the end.

06:32

That’s just the hazards of doing math with floats. For completion’s sake, let me just show you the pow() function from the math library to do the same thing.

06:45

Not surprisingly, you get the same result.

06:50

Next up, how computers calculate these roots.

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!

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:

 

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!

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:

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

Дополнительно:  Centos запуск из под root

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:

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

 

The Square Root of Zero

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

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.

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:

Traceback (most recent call last): File , line , in
: 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:

Python Pit Stop: Tennis Ball Hit From Baseline

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:

Python Pit Stop: Tennis Ball Returned At 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:

Python Pit Stop: Solving For The Hypotenuse Using The Square Root

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:

Pythagorean Theorem: Solve For C

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

 

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.

  • 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!

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

This tutorial serves as a generic introduction to python and a brief introduction to the high-energy physics analysis package
«pyROOT». It is designed to take about 2 hours to read through and run the examples. That is just enough time to get started with python, have a feel for how the language works and be able to write and run simple analysis programs. I’ve not attempted to cover everything including coding best practices. Please note also that as most of the high energy physics software runs in python version 2, this tutorial uses the python version 2 syntax.

1) What is python?

From the python website:

Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Its high-level built in data structures, combined with dynamic typing and dynamic binding, make it very attractive for Rapid Application Development, as well as for use as a scripting or glue language to connect existing components together. Python’s simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance. Python supports modules and packages, which encourages program modularity and code reuse. The Python interpreter and the extensive standard library are available in source or binary form without charge for all major platforms, and can be freely distributed.

Often, developers fall in love with Python because of the increased productivity it provides. Since there is no compilation step, the edit-test-debug cycle is incredibly fast. Debugging Python programs is easy: a bug or bad input will never cause a segmentation fault. Instead, when the interpreter discovers an error, it raises an exception. When the program doesn’t catch the exception, the interpreter prints a stack trace. A source level debugger allows inspection of local and global variables, evaluation of arbitrary expressions, setting breakpoints, stepping through the code a line at a time, and so on. The debugger is written in Python itself, testifying to Python’s introspective power. On the other hand, often the quickest way to debug a program is to add a few print statements to the source: the fast edit-test-debug cycle makes this simple approach very effective.

Breaking this down:

  • High level — Programmers can write code that is agnostic to the underlying hardware or operating system
  • Built in data structures — Python has a great number of built in types. In addition to the usual ints and floats the built in string class for example is extremely powerful. As well as this, the syntax for creating, loops and lists and other collection objects is more natural than for older languages. Developers can use their available time more wisely by dealing with high level abstractions rather than low-level types.
  • Python is «interpreted» — Meaning no compilation step is needed.
    [**] Python can and is often used in place of more traditional shell and perl scripts since it has almost as powerful string parsing abilities but much more straightforward syntax.
    [**] In addition, the type of an object is determined when the script runs. The amount of typing is much reduced (no more «const int* blah = getBlah();»). This can allow rapid-prototyping, i.e. writing a function/class/program to perform a desired task quickly. It does, however, introduce a class of bugs that strongly typed languages do not automatically suffer from.
    [**] Programs written entirely in python also run more slowly than well-written compiled code. However, if this turns out to be a problem there ways to re-write only parts of the program in C/C++. This is exactly how «pyROOT» (discussed below) interfaces to ROOT.
  • Python supports modules — Because python is quite an easy and well used open language there are thousands of people who have written extensions or «modules» to perform certain tasks well. With python is is always worth a quick google to see whether someone has written something to do pretty much what you want. Because python is also quite readable and distributed and run from it’s source code, it is usually quite easy to see exactly what a library is doing.

2) Python vs c++

Normally, start by using python unless you need to use C++ for some reason. Those reasons include:

  • Someone has already done >75% of the work in C++.
  • I don’t know any python (lets fix that).
  • I have profiled my python code and realised that doing «X» operation is really slow, I have already re-written the python to be faster and it is still a problem.
  • I am writing a non-linear program and the compile-time error-trapping and type checking that one gets for free with a compiler is important to me to catch edge-case bugs.

Consider two programs, one in C++ and one in python

#A program written in python
#!/usr/bin/python
print «Hello World»

There is often a lot less to type when writing a python program or script. There are fewer steps to remember and get wrong (write and run vs write, compile and run). Perhaps most important when it comes to finding errors is the clarity of python code.

3) Running the python interpreter

Python’s main power comes with how easy it is to get something that works. Part of that power is the rapid prototyping that is made possible by the interpreter. Python comes with a native interpreter that can be used simply by running:

We can quit with Ctrl+D.

However, the basic interpreter lacks a few features. A better one is «ipython».

Python has a few built in types, such as your usual ints, floats. It also naively supports quite complex strings and string modification functions. Lets start with something simple to demonstrate using the the variable «aString» to store the text «hello world»:

ipython > print ‘hello world’
hello world
ipython > aString=’hello world’
ipython > print aString
hello world

The interpreter also offers standard «shell-like» features such as tab completion and history — try tab completion by typing «aSt» in the example above and then tab before pressing enter. In addition, the history buffer can be scrolled by pressing up/down arrows or searched with ‘Ctrl+R’, starting to type the command, e.g. the first part, «hell» of «hello» in the example above and then Ctrl+R to scroll through the matches.

> cat mySession.py
# coding: utf-8

print ‘hello world’

You can then re-run your old code with:

If you are running on a machine integrated with a batch system such as pplxint8/9, you can scale up and out your python session onto the batch nodes. This would be achieved by adding «#!/usr/bin/python as the first line in your saved «mysession.py» file and then running qsub mysession.py.

Python types often come with their own documentation. This can be accessed using help(type) or even help(variable) from the command line. Just to view all of the symbols defined by the type, dir(type/variable) will also work.

4) Basic Syntax

Comments in python are denoted with a hash (‘#’) symbol. The text between the hash symbol and the end of the current line is not treated as code. Instead it is used to provide a hint to people reading your code as to what it does. As a rule of thumb, about 1/3 of the text in your python programs should normally be in comments.

Variable types (eg int, float) are rarely explicitly specified in python except when they are first defined. Python will decide for you what type a variable is. We say that the variables in python are not strongly typed (however the values are). To create a new variable, just write a name that you want to refer to it by and then use the assign (=) operator and give it a value. E.g to assign the value ‘2’ to the identifier ‘myNumber’, simply write ‘mynumber = 2’. You can then use myNumber anywhere in your code and the interpreter will treat every occurrence just as if you had directly written the number ‘2’. Unlike some languages, no type needs to be specified and no special characters are needed to indicate that you want the variable to be expanded to it’s value.

5) Built-in Types and simple functions

Python has a range of built in types and has powerful introspection features. In python it is rare to specify the type of a variable directly. Instead, just let python decide.

Python function calls, similar to other languages, use parenthesis «()» to indicate the function. If the function takes arguments, the arguments go into the parenthesis separated by commas.

The type() function can be used to determine the type at run-time. Some examples are below.

It is also easy change the type of a variable just by reassigning a new variable of a different type, e.g.

Debugging tip: This ability to change the type of a variable at run-time is a powerful feature, but it can also be dangerous and its misuse has in the past actually doubled the amount of time we spent working on one project. When the type() function is scattered into your debugging statements together with a convention of storing the variable type somewhere in the variable name, one can often spot errors caused by passing the wrong type of variable to a function more quickly. When the type should absolutely not change, I choose to use the first letter of the variable name to indicate its type — see code lines 33-44 above for examples.

6) Containers

Lists

Python’s most basic conventional container is a list. A list may contain mixed parameter types and may be nested. Elements within the list can be accessed by using the integer corresponding to that element’s position in the list, starting from ‘0’.

We can also re-assign elements of the list, and add to the list with the append() member function. The len() function gives the length of containers.

The «append» function illustrates «member functions». Member functions of classes modules can be accessed by giving the class instance name or module name post-fixed by a dot and then the member function or variable: e.g. myString.append('value').

You can use either double quotes or single quotes to enclose a string. You can use this fact to include quotes in your string, e.g.

print 'and they said "python strings are very powerful"'

More on strings

Though the variables are not strongly typed, the values are. The operator (*) is a duplicate operator for the string.

Dictionary

The python dictionary class is more powerful than the list type. You can use any type as the index, not just an integer. In the example below, we emulate the above list using a dict then add on an element using a string type as the index.

7) Loops and conditionals

«if» conditional

The syntax for a python if statement is:

if 1 == a:
#do something
#else if does not work in python, use elif
elif 1 == b:
#do something else
else:
#do this thing

Loops

Loops in python can be controlled by the for and while loops. The in keyword can be used to generate a sequence of values directly from the list.

Here is an example of both for and while loops:

for val in l:
print val, ‘ is l from for loop’

The continue statement tells the code to jump straight to the next iteration of the loop and stop executing any more code in this iteration. The break statement jumps straight out of the loop and executes no further code in the for or while loop. Notice also I have introduced the ‘not’ keyword, which negates the expression it prefixes. I have also introduced the rather standard shorthand for count=count+1, namely count+=1

8) File I/O

A common problem is that a text file containing data formatted in a certain way is given to you as input data. Your job will need to parse and analyse this datafile.

#open source file for reading
source = open(‘data.txt’,’r’)
#open dest file for writing
dest = open(destfile.txt’,’w’)
#loop over all the lines in the first file
#and write both to the screen and to the destination file
for line in source:
#Print to the screen
print line
#Write to the file
dest.write(line)
#Always close the files
source.close()
dest.close()

Now see demo3 in the attached source code

9) Writing functions

#!/usr/bin/python
###Function demo 1####
#First define the function that will be used
def myFirstFunction(myParam1, myParam2=’default’):
#Indent 4 spaces
print myParam1
#Check whether the second parameter is the default one or not
if ‘default’ == myParam2:
#Indent 4 spaces
print ‘I was not passed a second parameter’
else:
print ‘I was passed a second parameter, it was: ‘, myParam2
#Return a string saying everything went well
#Note, convention is to return the integer ‘0’ if the function behaved as expected
#or a non-zero integer if there was an error.
return ‘OK’

Дополнительно:  Что такое root доступ в сбербанке онлайн

# no indent
# the first non-indented (or commented) line without the def or class keyword is the
# entry point of the code
print ‘About to run my function’
myFirstFunction(‘I am running in a function!!’)
retval=myFirstFunction(‘Passing Another Parameter’,'»this text»‘)
print ‘»myFirstFunction» returned «‘, retval, ‘»‘

Now see demo2 in the attached source code

10) Keywords

So far we have covered most of what is needed to write a simple program, and it is beyond the scope of this introduction to cover all python reserved words. However, a list of the python reserved keywords is given here for completeness so that the reader can look up these online.

and del for is raise
assert elif from lambda return
break else global not try
class except if or while
continue exec import pass yield
def finally in print

Note that although the identifier as can be used as part of the syntax of import statements, it is not currently a reserved word.

In some future version of Python, the identifiers as and None will both become keywords.

11) Modules and passing command line arguments to python

Python has a lot of built-in functionality, but that is nothing compared to what exists in the extensions or ‘modules’ than have been written for python. I cannot tell you how to use them all, or even what ones are available. Try googling what you want to do, and usually you will find a module to do it. Once you know which module you want, fire up the (i)python interpreter and type import module-name, where module-name is the name of the module e.g. «sys» or «os». We can install extra python modules on the particle Linux systems as required. You can also install your own personal copy in a python «virtual environment», which is often more appropriate. See the next main section for details.

The modules often come with their own documentation. This can be accessed using help(module-name) from the command line. Just to view all of the symbols defined by the module, dir(module-name) will also work. Usually googling «python module-name» is just as good or better! A notable exception to all that is when running pyROOT (i.e. importing ROOT into python).

The sys module

A heavily used module is the ‘sys’ module, which is most often used to pass information from the calling shell to python and vice versa.

#!/usr/bin/python
###Module demo 1###
import sys
#print out the help documentation for sys — there is a lot!
help(sys)

#!/usr/bin/python
###Module demo 2###
import sys
#get the number of parameters passed to the python program
argc=len(sys.argv)
#Loop over the arguments passed to the program and print them out.
#Note that the first argument is always the name of the running program.
for arg in sys.argv:
print arg

#Exit with a status of ‘0’ to indicate to the shell that the python program ran OK.
sys.exit(0)

You should also familiarise yourself with the «os» module, which is also used a lot.

Now see demo4 in the attached source code

12) Extending python with additional modules and running newer python versions

  1. Add additional modules that are not already installed on the system
  2. Run newer versions of modules than the system provides
  3. Run a newer version of python than the system provides
  4. Have several different projects with potentially conflicting python module requirements

cd $HOME
virtualenv —system-site-packages myVirtualenv
. $HOME/myVirtualenv/bin/activate
pip install —upgrade pip setuptools

At this point, you will notice your prompt change to indicate you are running in a virtualenv. You can install new python modules into the virtual environment. Lets now look for and install a package to help with plotting in numpy

pip search numpy
pip install numpy

I can now run some numpy code

Running newer versions of python in your virtualenv

On most university and research lab systems, IT will be able to install a new version of python if requested, so I wont cover that here. To make use of these versions of python all you need is the path to the new python version. For example in physics.

module load python/2.7
virtualenv —system-site-packages -p `which python` ~/myPython27Venv

Running python3 virtualenvs

For python 3, virtualenvs have been replaced. Some of the early versions of python 3 had various issues, but from python 3.4.5 things seem very smooth with the new tool «pyvenv». It is very similar to virtualenvs.

To set up a python 3.4.5 pyvenv:

module load python/3.4.5
pyvenv-3.4 myVirtualenv2
. myVirtualenv2/bin/activate
pip install —upgrade pip setuptools
pip install scipy

To load it again for re-use:

module load python/3.4.5
. myVirtualenv2/bin/activate

Multiple simultaneous environments (advanced)

In a current writable directory:

#Note, in this case ensure that you can get the defaults from the system if they exist with —system-site-packages
virtualenv —system-site-packages layeredenv
. $HOME/layeredenv/bin/activate
pip install envplus
export WORKON_HOME=$HOME/layeredenv
export EDITOR=vim
envplus add /network/group/particle/itstaff/numpy_virtualenv

. layeredenv/bin/activate
pip install YOURMODULE
ipython
import numpy

13) pyROOT — for PP students only

Up to now, this tutorial has been quite generic. This part is for particle physics students.

Some helpful chap has wrapped up the entirety of ROOT into a python module. Since python syntax is more natural than C++ and the python interpreter does not suffer from as many bugs and problems with non-standard syntax as the ‘CINT’ interpreter, I recommend using pyROOT instead of CINT when you are starting any program from scratch. People may suggest that python is slower than C++. It is, but that statement applies to compiled C++ not CINT, for the most part it doesn’t matter and also you need to know C++ well to make it very fast. At the end of the day, any really slow parts of your code can be re-written in C(++) if absolutely necessary. Remember two generalizations about C++ and general execution times.

1) The average C++ software engineer writes 6 lines of useful, fully tested and debugged code per day.
2) 80% of the CPU time will be spent on 20% of your code even after you have optimised the slow parts.

Lets begin by setting up root. To use pyROOT, the C++ libraries must be on your PYTHONPATH. This is set up automatically by the most recent Oxford set-up scripts.

In the case of pyROOT a deliberate decision was made by the developers not to import all of the symbol names when import is run. Only after the symbol is first used is it available to the interpreter (e.g. via tab-complete or help()).

Lets now import the ROOT module into root and use it to draw a simple histogram.

Debugging tip: If you are changing the version of python (sometimes implicit when altering your root version) you may want to eithe re-create your ipython profile (rm -r ~/.ipython; ipython profile create default) or run ROOT.gROOT.Reset() to allow the graphics to be displayed.

To use root in the ipython interpreter and create, fill and draw a basic histogram:

You can view the contents of rootHist.py using an editor like «emacs».

To fill an ntuple/Tree

import ROOT
ROOT.gROOT.Reset()
# create a TNtuple
ntuple = ROOT.TNtuple(«ntuple»,»ntuple»,»x:y:signal»)
#store a reference to a heavily used class member function for efficiency
ntupleFill = ntuple.Fill

# generate ‘signal’ and ‘background’ distributions
for i in range(10000):
# throw a signal event centred at (1,1)
ntupleFill(ROOT.gRandom.Gaus(1,1), # x
ROOT.gRandom.Gaus(1,1), # y
1) # signal

# throw a background event centred at (-1,-1)
ntupleFill(ROOT.gRandom.Gaus(-1,1), # x
ROOT.gRandom.Gaus(-1,1), # y
0) # background
ntuple.Draw(«y»)

Instead of launching the script from the Linux command line, it is possible to run the script from within the «ipython» interpreter and keep all your variables so that you can continue to work.

shell> ipython
%run root-hist.py

Also, a feature of the root module means that the ntuple and the new canvas appears in the ROOT name-space for you to continue using it in your program too.

You can also find your objects again using the TBrowser.

The GUI that pops up has a number of pseudo-directories to look in. Open the one that says ‘root’ in the left pane and navigate to ROOT Memory—>ntuple. You can double click on your histograms to draw them from here.

By right-clicking on the name of your ntuple (in this case just ‘ntuple’) and navigating to ‘Start Viewer’, you can drag and drop the variables to draw as a histogram or apply as a cut. Drag signal into the box marked with scissors and x onto the ‘x’ box. Click the purple graph icon to Draw. You may have to create the canvas first. You can do that from the new TBrowser — See the «Command» box in figure 1.

Edit cut
Figure 1: Editing a cut and creating a canvas from the TBrowser

New canvas
Figure 2: Making a new canvas from the Browser

Draw selections

Figure 3: The draw current selection box

Filling an ntuple

The attached source code contains a workable demonstration of working with ROOT ntuples, covering:

Now work through demo 5 in the attached source code

Garbage collection (specific to ROOT but not specific to pyROOT)

Normally, garbage collection is classed as an advanced concept, however in my experience most of the annoyance of ROOT in general was to do with seemingly random crashes. Most of these were actually due to the object I was using disappearing at various point in the program. This was due to misunderstanding ROOT’s object ownership model, which functions as a poor-mans garbage collection. This happens outside of python.

Root objects are not persistent. They are owned by the directory they «exist» within. In this case the histogram is actually owned by the canvas (which is itself a directory in ROOT), but the ntuple only contains a reference to it. TDirectory and TPad classes and derived classes count as directories in this model.

One way to rescue the situation, if you want the histogram to outlive the canvas you can make a copy:

or you can remove the histogram from the pad before you close it

htemp=ROOT.ntuple.GetHistogram()
##Remove the histogram from the list of objects owned by c1
##Try moving the histogram inside canvas around (to force a re-draw). It disappears.
ROOT.c1.GetListOfPrimitives().Remove(htemp)
###Now close the canvas
htemp.Draw()
##Don’t forget to remove the histogram from the list of canvas primitives before closing the next canvas!
print htemp

Chapter 8 of the ROOT manual details more on object ownership.

14) Additional Resources:
Official python tutorial
Google python tutorial complete with videos. Videos cover the simple topics in quite a lot of depth.
pyroot at cern

15) Optimization tricks

The most important thing is to do good Physics, fast computer code comes later. However, since I am in charge of looking after the batch systems, I have a vested interest in your code not crippling the entire computing system. This exercise also gives more practice importing and using someone elses modules (profiler and stats).

There is one place where python is very slow and there is an easy fix. That is when running code in a loop. This section will demonstrate that slowdown and give a solution to the problem.

Generally only optimize where it is needed. Even the world experts can’t guess where this will be needed 100% of the time.

To find what is taking the time, a little tool called cProfile exists. Run this example program to see how it works. Spend the time looking only at optimizing the functions that are taking time. I have two functions, foo and bar. I want to know which to optimize. From the output, it looks like bar needs optimizing.

import cProfile
#Define 3 functions that do something. In this case the content of the functions is not the relevant thing.

def add(a):
a+=1
def bar():
print ‘y’
for x in range(2000000):
add(x)

def foo():
a=0
for i in range(10):
print i
for j in range(100000):
a+=j
#calling bar from within foo
bar()

#The point of this exercise is the profiler. Declare a new profiler called ‘fooprof’ which will immediately run the foo() function like this:
cProfile.run(‘foo()’,’fooprof’)
#To output the results of the profiler, we need pstats
import pstats
pf = pstats.Stats(‘fooprof’)
#Print out the sorted stats
print pf.sort_stats(-1).print_stats()

Common cause of python slowdowns

There is a quick way to speed up python code to play a trick when repeatedly using a class member function. Store the class member function function in a variable and use that to make the function call.

Note, this section is about optimizing a function being called repeatedly in a loop. The function could have been doing anything, it just so happends I chose addition. This section is not about optimizing addition.

class adder:
def add(self, x):
x+=1

def add(x):
x+=1

def foo():
print ‘y’

#take a reference to the class member function
adderadd=myadder.add

for x in range(200000):

#Fastest is to use a function without the class
add(x)

#slowest is to make python look up the class and function every time
myadder.add(x)

#Almost the fastest, python no longer needs to look up where the class member function ‘is’ each time as the result of that lookup is cached (in adderadd).
adderadd(x)

cProfile.run(‘foo()’,’fooprof’)
import pstats
p = pstats.Stats(‘fooprof’)
print p.sort_stats(-1).print_stats()

We learn from this that by creating a local reference to a class member function for our innermost loops, we can speed up python dramatically.

#SLOW
for i in range(10000):
myclass.foo()

#FAST
mcfoo=myclass.foo
for i in range(10000):
mcfoo()

All of this is available in demo 6 in the attached source code

16) Ipython notebooks

Ipython notebooks allows you to run python in a web-browser and save your sessions. You can connect from the interactive machine on which you are running and any graphics will pop up on your X display (i.e. not in the browser).

As with all web applications, anyone connecting to the application can do whatever you can do.

To avoid this, there is some additional set-up to do, which you should do if you want to make it hard for anyone connected to the machine to delete all of your files (for example). So set a password on the browser. This is probably safe enough for use on the interactive machines if you connect from the firefox webbrowser that is installed on the machine on which you run the notebook.

Make a little python script that does this:

##############makepass.py############
#!/bin/env python
from IPython.lib import passwd
print passwd()

Create an ipython profile to include the settings for the notebook.

> ipython profile create default

You may need to remove the existing ipython configuration that you have with

>rm -fr ~/.ipython

c.NotebookApp.password = u'longoutputstring'

Where longoutputstring is the whole string returned to you when you ran the little makepass.py script above.

Be absolutely sure nobody can read this file:

chmod og-rwx $HOME/.config/ipython/profile_default/ipython_notebook_config.py

You can then run the notebook (on pplxint8) with:

> module load root/5.34.09_gcc4.6
> module load zeromq/3.2.4
> ipython notebook

jupyter

An improvement on python notebooks is ‘jupyter’. I found this difficult to install, but works in python3. To use jupyter:

module load python/3.4.4
pyvenv jupytertest
. jupytertest/bin/activate
pip3 install —upgrade pip
pip install jupyter
jupyter notebook

EDIT

Overcoming the issues and limits of this method/implementation:

For smaller numbers, you can just use all the other methods from other answers. They generally use floats, which might be a loss of precision, but for small integers that should mean no problem at all. All of those methods that use floats have the same (or nearly the same) limit from this.

If you still want to use this method and get float results, it should be trivial to convert this to use floats too. Note that that will reintroduce precision loss, this method’s unique benefit over the others, and in that case you can also just use any of the other answers. I think the newton’s method version converges a bit faster, but I’m not sure.

For larger numbers, where loss of precision with floats come into play, this method can give results closer to the actual answer (depending on how big is the input). If you want to work with non-integers in this range, you can use other types, for example fixed precision numbers in this method too.

Fractional exponent

The power operator (**) or the built-in pow() function can also be used to calculate a square root. Mathematically speaking, the square root of a equals a to the power of 1/2.

The power operator requires numeric types and matches the conversion rules for binary arithmetic operators, so in this case it will return either a float or a complex number.

>>> 9 ** (1/2)
3.0
>>> 9 ** .5 # Same thing
3.0
>>> 2 ** .5
1.4142135623730951

(Note: in Python 2, 1/2 is truncated to 0, so you have to force floating point arithmetic with 1.0/2 or similar. See Why does Python give the «wrong» answer for square root?)

Дополнительно:  Компьютерра: Вызываем синий экран смерти Windows

This method can be generalized to nth root, though fractions that can’t be exactly represented as a float (like 1/3 or any denominator that’s not a power of 2) may cause some inaccuracy:

>>> 8 ** (1/3)
2.0
>>> 125 ** (1/3)
4.999999999999999

Project description

https://img.shields.io/pypi/v/rootpy.svg
https://travis-ci.org/rootpy/rootpy.png
https://zenodo.org/badge/doi/10.5281/zenodo.18897.svg

Python has become the language of choice for high-level applications where
fast prototyping and efficient development are important, while
glueing together low-level libraries for performance-critical tasks.
The PyROOT bindings introduced
ROOT into the world of Python, however, interacting
with ROOT in Python should not feel like you are still writing C++.

The rootpy project is a community-driven initiative aiming to provide a more
pythonic interface with ROOT on top of the existing PyROOT bindings. Given
Python’s reflective and dynamic nature, rootpy also aims to improve ROOT design
flaws and supplement existing ROOT functionality. The scientific Python
community also offers a multitude of powerful packages such as
SciPy,
NumPy,
matplotlib,
scikit-learn,
and PyTables,
but a suitable interface between them and ROOT has been lacking. rootpy
provides the interfaces and conversion mechanisms required to liberate your
data and to take advantage of these alternatives if needed.

Key features include:

  • Improvements to help you create and manipulate trees, histograms, cuts
    and vectors.

  • Dictionaries for STL types are compiled for you automatically.

  • Redirect ROOT’s messages through Python’s logging system.

  • Optionally turn ROOT errors into Python exceptions.

  • and methods on ROOT objects are also properties.

  • Easy navigation through ROOT files. You can now access objects with
    , for example.

  • Colours and other style attributes can be referred to by descriptive strings.

  • Provides a way of mapping ROOT trees onto python objects and collections.

  • Plot your ROOT histograms or graphs with matplotlib.

  • Conversion of ROOT trees into NumPy ndarrays
    and recarrays
    through the related root_numpy
    package.

  • Conversion of ROOT files containing trees into
    HDF5 format with
    PyTables.

  • , a Bash-like shell environment for the ROOT file, very useful for
    quick ROOT file inspection and interactive plotting.

  • , a command for common tasks such as summing histograms or drawing
    tree expressions over multiple files, listing the contents of a file,
    or inspecting tree branches and their sizes and types.

Disclaimer: this is for a more specialised use-case. This method might not be practical in all circumstances.

  • can find integer values (i.e. which integer is the root?)
  • no need to convert to float, so better precision (can be done that well too)

I personally implemented this one for a crypto CTF challenge (RSA cube root attack),where I needed a precise integer value.

The general idea can be extended to any other root.

def int_squareroot(d: int) -> tuple[int, bool]: """Try calculating integer squareroot and return if it's exact""" left, right = 1, (d+1)//2 while left<right-1: x = (left+right)//2 if x**2 > d: left, right = left, x else: left, right = x, right return left, left**2==d

Python Integer Square Root

There may be times when you want to return an integer value when you are calculating the square root of a value. Keep in mind, that unless you’re working with specific numbers (“perfect squares”), this won’t be the true square root of that number.

Python’s math library comes with a special function called isqrt(), which allows you to calculate the integer square root of a number.

Let’s see how this is done:

# Calculating the integer square root with Python
from math import isqrt
number = 27
square_root = isqrt(number)
print(square_root)
# Returns: 5

Similar to our example of using the sqrt() function, the isqrt() returned a value. When we passed in 27, the function returned 5! This is odd, since that’s actually the square root of 25.

The reason for this is that the isqrt() floors the value to its nearest integer.

Acknowledgements

Support for this work was provided by NSF cooperative agreement OAC-1836650 (IRIS-HEP), grant OAC-1450377 (DIANA/HEP), and PHY-2121686 (US-CMS LHC Ops).

Thanks especially to the gracious help of Uproot contributors (including the original repository).

💻: code, 📖: documentation, 🚇: infrastructure, 🚧: maintainance, ⚠: tests/feedback, 🤔: foundational ideas.

Installation for developers

Uproot is an ordinary Python library; you can get a copy of the code with

git clone https://github.com/scikit-hep/uproot5.git

and install it locally by calling pip install -e . in the repository directory.

If you need to develop Awkward Array as well, see its installation for developers.

Installation

Uproot can be installed from PyPI using pip.

pip install uproot

Uproot is also available using conda.

conda install -c conda-forge uproot

If you have already added conda-forge as a channel, the -c conda-forge is unnecessary. Adding the channel is recommended because it ensures that all of your packages use compatible versions (see conda-forge docs):

conda config --add channels conda-forge
conda update --all

✔ Output 💡 CLICK BELOW & SEE ✔

Output1

Output2

Mark Dickinson's user avatar

answered May 7, 2022 at 17:21

Shubham-Misal's user avatar

Python Square Root Using Exponentiation

In an earlier section of this tutorial, you learned that the square root is the base of a square number. Similarly, we can write the square root of a number n as n1/2.

In Python, we can raise any number to a particular power using the exponent operator **.

Let’s see how we can get the Python square root without using the math library:

# Use exponents to calculate a square root
number = 25
square_root = number**(1/2)
print(square_root)
# Returns: 5.0

You can see here that this returns the same value as if we had used the sqrt() function.

Similarly, we could also have written number**0.5.

Important tip: If you’re using Python 2, you will need to ensure you’re using float division and write number**(1./2). This is because Python 2 floors to an integer. As such, simply writing number**(1/2) would actually result in number**(0).

NumPy

>>> import numpy as np
>>> np.sqrt(25)
5.0
>>> np.sqrt([2, 3, 4])
array([1.41421356, 1.73205081, 2. ])

Negative

For negative reals, it’ll return nan, so np.emath.sqrt() is available for that case.

>>> a = np.array([4, -1, np.inf])
>>> np.sqrt(a)
<stdin>:1: RuntimeWarning: invalid value encountered in sqrt
array([ 2., nan, inf])
>>> np.emath.sqrt(a)
array([ 2.+0.j, 0.+1.j, inf+0.j])

Another option, of course, is to convert to complex first:

>>> a = a.astype(complex)
>>> np.sqrt(a)
array([ 2.+0.j, 0.+1.j, inf+0.j])

What is a Square Root?

In math, you often hear of the square of a number, which is often represented by a superscript 2. So, a square of a number n, would be represented by n2. The square of a number is calculated by multiplying the number by itself.

Because of this, the square of a number will always have some properties:

  • It will always be a positive number (since the product of two negative numbers is a positive number)
  • Can be either an integer or a floating point number

But why are we learning about squares, if this article is about the square root? The square root is much easier to understand when you understand the square of a number. This is because the square root is, quite literally, the root of the square.

What I mean by this, is that the square root of n2 is n. The square root of a number, say y, is often represented as √y. The square root is used in many different mathematical and scientific functions, such as the pythagorean theorem, which calculates the length of the hypotenuse of a right angle triangle.

Now that you have a solid understanding of what the square root is, let’s dive into how to calculate the square root using Python!

Want to learn something else? Want to learn how to calculate the standard deviation in Python? Check out my in-depth tutorial here!

Square Root Limitations – Negative Numbers and Zero

In the two sections below, you’ll learn about two special cases of square roots. In particular, you’ll learn how to calculate the square root of zero, as well as what happens when you try to calculate the square root of a negative number!

Calculate the Square Root of Zero Using Python

Now, let’s see how we can use Python to calculate the value of the square root of zero. We can do this, again, using the sqrt() function:

# Calculating the square root of zero
from math import sqrt
number = 0
square_root = sqrt(number)
print(square_root)
# Returns: 0.0

We can see from the example above that calculating the square root of zero does not cause an error.

Calculating the Square Root of Negative Numbers with Python

Finally, let’s take a look at what happens when we try to calculate the square root of negative numbers with Python. You’ll remember, from the earlier section, that squares are always positive numbers. So, what happens when we try to take the square root of a negative number? Let’ give this a shot!

# Calculating the square root of a negative number
from math import sqrt
number = -25
square_root = sqrt(number)
print(square_root)
# Returns: ValueError: math domain error

We can see that trying to calculate the square root of a negative number returns a ValueError. The reason that this happens is because the square root of negative numbers simply don’t exist!

In the next section, you’ll learn how to calculate the integer square root.

SymPy

Depending on your goal, it might be a good idea to delay the calculation of square roots for as long as possible. SymPy might help.

SymPy is a Python library for symbolic mathematics.

import sympy
sympy.sqrt(2)
# => sqrt(2)

This doesn’t seem very useful at first.

But sympy can give more information than floats or Decimals:

sympy.sqrt(8) / sympy.sqrt(27)
# => 2*sqrt(6)/9

Also, no precision is lost. (√2)² is still an integer:

s = sympy.sqrt(2)
s**2
# => 2
type(s**2)
#=> <class 'sympy.core.numbers.Integer'>

In comparison, floats and Decimals would return a number which is very close to 2 but not equal to 2:

(2**0.5)**2
# => 2.0000000000000004
from decimal import Decimal
(Decimal('2')**Decimal('0.5'))**Decimal('2')
# => Decimal('1.999999999999999999999999999')

Sympy also understands more complex examples like the Gaussian integral:

from sympy import Symbol, integrate, pi, sqrt, exp, oo
x = Symbol('x')
integrate(exp(-x**2), (x, -oo, oo))
# => sqrt(pi)
integrate(exp(-x**2), (x, -oo, oo)) == sqrt(pi)
# => True
sympy.N(sympy.sqrt(2), 1_000_000)
# => 1.4142135623730950488016...........2044193016904841204

wjandrea's user avatar

9 gold badges59 silver badges80 bronze badges

answered Jan 21, 2022 at 14:38

Eric Duminil's user avatar

Eric Duminil

9 gold badges69 silver badges123 bronze badges

Edge cases

Negative and complex

Exponentiation works with negative numbers and complex numbers, though the results have some slight inaccuracy:

>>> (-25) ** .5 # Should be 5j
(3.061616997868383e-16+5j)
>>> 8j ** .5 # Should be 2+2j
(2.0000000000000004+2j)

Note the parentheses on -25! Otherwise it’s parsed as -(25**.5) because exponentiation is more tightly binding than unary negation.

Meanwhile, math is only built for floats, so for x<0, math.sqrt(x) will raise ValueError: math domain error and for complex x, it’ll raise TypeError: can't convert complex to float. Instead, you can use cmath.sqrt(x), which is more more accurate than exponentiation (and will likely be faster too):

>>> import cmath
>>> cmath.sqrt(-25)
5j
>>> cmath.sqrt(8j)
(2+2j)

Precision

Both options involve an implicit conversion to float, so floating point precision is a factor. For example:

>>> n = 10**30
>>> x = n**2
>>> root = x**.5
>>> n == root
False
>>> n - root # how far off are they?
0.0
>>> int(root) - n # how far off is the float from the int?
19884624838656

Very large numbers might not even fit in a float and you’ll get OverflowError: int too large to convert to float. See Python sqrt limit for very large numbers?

Other types

Let’s look at Decimal for example:

Exponentiation fails unless the exponent is also Decimal:

>>> decimal.Decimal('9') ** .5
Traceback (most recent call last): File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for ** or pow(): 'decimal.Decimal' and 'float'
>>> decimal.Decimal('9') ** decimal.Decimal('.5')
Decimal('3.000000000000000000000000000')

Meanwhile, math and cmath will silently convert their arguments to float and complex respectively, which could mean loss of precision.

decimal also has its own .sqrt(). See also calculating n-th roots using Python 3’s decimal module

Download files

Source Distribution

Python Square Root Using math. sqrt

To calculate the square root in Python, you can use the built-in math library’s sqrt() function. This makes it very easy to write and to help readers of your code understand what it is you’re doing.

The sqrt() function takes only a single parameter, which represents the value of which you want to calculate the square root. Let’s take a look at a practical example:

# Using the sqrt() function to calculate a square root
from math import sqrt
number = 25
square_root = sqrt(number)
print(square_root)
# Returns: 5.0

Let’s explore what we’ve done here:

  1. We imported sqrt from math
  2. We declared a variable number, holding the integer value of 25
  3. We used the sqrt function to create a new variable square_root
  4. Finally, we printed the value of square_root, which gave us the value of 5.0

Check out some other Python tutorials on datagy, including our complete guide to styling Pandas and our comprehensive overview of Pivot Tables in Pandas!

Edit 2, on other answers

Currently, and afaik, the only other answer that has similar or better precision for large numbers than this implementation is the one that suggest SymPy, by Eric Duminil. That version is also easier to use, and work for any kind of number, the only downside is that it requires SymPy. My implementation is free from any huge dependencies if that is what you are looking for.

answered Jan 21, 2022 at 17:12

Uncle Dino's user avatar

Uncle Dino

1 gold badge7 silver badges23 bronze badges

Arbitrary precision square root

This variation uses string manipulations to convert a string which represents a decimal floating-point number to an int, calls math.isqrt to do the actual square root extraction, and then formats the result as a decimal string. math.isqrt rounds down, so all produced digits are correct.

The input string, num, must use plain float format: ‘e’ notation is not supported. The num string can be a plain integer, and leading zeroes are ignored.

The digits argument specifies the number of decimal places in the result string, i.e., the number of digits after the decimal point.

from math import isqrt
def str_sqrt(num, digits): """ Arbitrary precision square root num arg must be a string Return a string with `digits` after the decimal point Written by PM 2Ring 2022.01.26 """ int_part , _, frac_part = num.partition('.') num = int_part + frac_part # Determine the required precision width = 2 * digits - len(frac_part) # Truncate or pad with zeroes num = num[:width] if width < 0 else num + '0' * width s = str(isqrt(int(num))) if digits: # Pad, if necessary s = '0' * (1 + digits - len(s)) + s s = f"{s[:-digits]}.{s[-digits:]}" return s

Test

print(str_sqrt("2.0", 30))

Output

1.414213562373095048801688724209

For small numbers of digits, it’s faster to use decimal.Decimal.sqrt. Around 32 digits or so, str_sqrt is roughly the same speed as Decimal.sqrt. But at 128 digits, str_sqrt is 2.2× faster than Decimal.sqrt, at 512 digits, it’s 4.3× faster, at 8192 digits, it’s 7.4× faster.

Here’s a live version running on the SageMathCell server.

answered Jan 25, 2022 at 14:39

PM 2Ring's user avatar

PM 2Ring

6 gold badges82 silver badges180 bronze badges

Math. sqrt()

The math module from the standard library has a sqrt function to calculate the square root of a number. It takes any type that can be converted to float (which includes int) as an argument and returns a float.

>>> import math
>>> math.sqrt(9)
3.0

Find square-root of a number

while True: num = int(input("Enter a number:\n>>")) for i in range(2, num): if num % i == 0: if i*i == num: print("Square root of", num, "==>", i) break else: kd = (num**0.5) # (num**(1/2)) print("Square root of", num, "==>", kd)

Enter a number: 24
Square root of 24 ==> 4.898979485566356
Enter a number: 36
Square root of 36 ==> 6
Enter a number: 49
Square root of 49 ==> 7

Getting help

Start with the tutorials and reference documentation.

Dependencies

Uproot’s only strict dependencies are NumPy and packaging. Strict dependencies are automatically installed by pip (or conda).

Awkward Array is highly recommended and is automatically installed by pip (or conda), though it is possible to use Uproot without it. If you need a minimal installation, pass --no-deps to pip and pass library="np" to every array-fetching function, or globally set uproot.default_library to get NumPy arrays instead of Awkward Arrays.

  • awkward: Uproot 5.x requires Awkward 2.x.

For ROOT files, compressed different ways:

  • lz4 and xxhash: if reading ROOT files that have been LZ4-compressed.
  • zstandard: if reading ROOT files that have been ZSTD-compressed.
  • ZLIB and LZMA are built in (Python standard library).

For accessing remote files:

  • xrootd: if reading files with root:// URLs.
  • HTTP/S access is built in (Python standard library).

For distributed computing with Dask:

  • dask: see uproot.dask.
  • dask-awkward: for data with irregular structure («jagged» arrays), see dask-awkward.

For exporting TTrees to Pandas:

  • pandas: if library="pd".
  • awkward-pandas: if library="pd" and the data have irregular structure («jagged» arrays), see awkward-pandas.

For exporting histograms:

  • boost-histogram: if converting histograms to boost-histogram with histogram.to_boost().
  • hist: if converting histograms to hist with histogram.to_hist().

Conclusion

In this post, you learned how to use Python to calculate a square root, both with and without the math.sqrt() function. You also learned what a square root is, what some of its limitations are, as well as how to calculate a Python integer square root.

Оцените статью
Master Hi-technology