In maths, if I wish to calculate 3 to the power of 2 then no symbol is required, but I write the 2 small: 3². In Python this operation seems to be represented by the ** syntax. If I want to go the other direction and calculate the 2nd root of 9 then in maths I need to use a
Tag: math
Arbitrary precision of square roots
I was quite disappointed when decimal.Decimal(math.sqrt(2)) yielded and the digits after the 15th decimal place turned out wrong. (Despite happily giving you much more than 15 digits!) How can I get the first m correct digits in the decimal expansion of sqrt(n) in Python? Answer Use the sqrt method on Decimal
Python: sort function breaks in the presence of nan
sorted([2, float(‘nan’), 1]) returns [2, nan, 1] (At least on Activestate Python 3.1 implementation.) I understand nan is a weird object, so I wouldn’t be surprised if it shows up in random places in the sort result. But it also messes up the sort for the non-nan numbers in the container, which is really unexpected. I asked a related question
Finding points on a rectangle at a given angle
I’m trying to draw a gradient in a rectangle object, with a given angle (Theta), where the ends of the gradient are touching the perimeter of the rectangle. I thought that using tangent would work, but I’m having trouble getting the kinks out. Is there an easy algorithm that I am just missing? End Result So, this is going to
Efficiently detect sign-changes in python
I want to do exactly what this guy did: Python – count sign changes However I need to optimize it to run super fast. In brief I want to take a time series and tell every time it crosses crosses zero (changes sign). I want to record the time in between zero crossings. Since this is real data (32 bit
How to round a number to significant figures in Python
I need to round a float to be displayed in a UI. e.g, to one significant figure: Is there a nice way to do this using the Python library, or do I have to write it myself? Answer You can use negative numbers to round integers: Thus if you need only most significant digit: You’ll probably have to take care
Fastest way to list all primes below N
This is the best algorithm I could come up. Can it be made even faster? This code has a flaw: Since numbers is an unordered set, there is no guarantee that numbers.pop() will remove the lowest number from the set. Nevertheless, it works (at least for me) for some input numbers: Answer Warning: timeit results may vary due to differences
What’s the best way to calculate a 3D (or n-D) centroid?
As part of a project at work I have to calculate the centroid of a set of points in 3D space. Right now I’m doing it in a way that seems simple but naive — by taking the average of each set of points, as in: where x, y and z are arrays of floating-point numbers. I seem to recall