How to get a cube root in Python [duplicate] - python

This question already has answers here:
How to find cube root using Python? [duplicate]
(3 answers)
Closed 6 years ago.
I saw this post recently, about getting square roots in python: How to calc square root in python?
I have used the sqrt(x) command, but I don't know how to make it work for cube roots and anything higher than that.
Also, I'm using Python 3.5.2.
Any help on this?

In Python, you may find floating cube root by:
>>> def get_cube_root(num):
... return num ** (1. / 3)
...
>>> get_cube_root(27)
3.0
In case you want more generic approach to find nth root, you may use below code which is based on Newton's method:
# NOTE: You may use this function only for integer numbers
# k is num, n is the 'n' in nth root
def iroot(k, n):
u, s = n, n+1
while u < s:
s = u
t = (k-1) * s + n // pow(s, k-1)
u = t // k
return s

Related

Sum of 1st N natural numbers in O(no. of digits in N)

I'm trying to write a program to find sum of first N natural numbers i.e. 1 + 2 + 3 + .. + N modulo 1000000009
I know this can be done by using the formula N * (N+1) / 2 but I'm trying to find a sort of recursive function to calculate the sum.
I tried searching the web, but I didn't get any solution to this.
Actually, the problem here is that the number N can have upto 100000 digits.
So, here is what I've tried until now.
First I tried splitting the number into parts each of length 9, then convert them into integers so that I can perform arithmetic operations using the operators for integers.
For example, the number 52562372318723712 will be split into 52562372 & 318723712.
But I didn't find a way to manipulate these numbers.
Then again I tried to write a function as follows:
def find_sum(n):
# n is a string
if len(n) == 1:
# use the formula if single digit
return int(int(n[0]) * (int(n[0]) + 1) / 2)
# I'm not sure what to return here
# I'm expecting some manipulation with n[0]
# and a recursive call to the function itself
# I've also not used modulo here just for testing with smaller numbers
# I'll add it once I find a solution to this
return int(n[0]) * something + find_sum(n[1:])
I'm not able to find the something here.
Can this be solved like this?
or is there any other method to do so?
NOTE: I prefer a solution similar to the above function because I want to modify this function to meet my other requirements which I want to try myself before asking here. But if it is not possible, any other solution will also be helpful.
Please give me any hint to solve it.
Your best bet is to just use the N*(N+1)/2 formula -- but using it mod p. The only tricky part is to interpret division by 2 -- this had to be the inverse of 2 mod p. For p prime (or simply for p odd) this is very easy to compute: it is just (p+1)//2.
Thus:
def find_sum(n,p):
two_inv = (p+1)//2 #inverse of 2, mod p
return ((n%p)*((n+1)%p)*two_inv)%p
For example:
>>> find_sum(10000000,1000000009)
4550000
>>> sum(range(1,10000001))%1000000009
4550000
Note that the above function will fail if you pass an even number for p.
On Edit as #user11908059 observed, it is possible to dispense with multiplication by the modular inverse of 2. As an added benefit, this approach no longer depends on the modulus being odd:
def find_sum2(n,k):
if n % 2 == 0:
a,b = (n//2) % k, (n+1) % k
else:
a,b = n % k, ((n+1)//2) % k
return (a*b) % k

Get the n-th double number from a given double in python

This question is similar to another question but I do not see how to extend the answer to that question in an easy way.
Here, I want to calculate the n-th double from a given double in Python.
The function takes an integer n, a double x, and outputs a double that is the n-th after x (or before, if n is negative). Is there an efficient way to do it?
Concretely, Let nth_fp_after be the function, then nth_fp_after(x,n) should equal to n times the application of nextafter (in C) to x; nth_fp_after(x,0) should be 'x', etc.
The answer of the question you pointed to is exactly the answer to your question. The answer solved the problem for for 64 bits float that are the python equivalent of C double.
Well, if you add the following
struct.unpack('!i',struct.pack('!f',x))[0]
to n and use it to call the function of the other answer, you should get it.
The full solution by modifying will look like:
import struct
def nth_fp(n, x=0.0):
if(x>=0):
m = n + struct.unpack('!Q',struct.pack('!d',x))[0]
else:
m = n - struct.unpack('!Q',struct.pack('!d',abs(x) ))[0]
if m < 0:
sign_bit = 0x8000000000000000
m = -m
else:
sign_bit = 0
if m >= 0x7ff0000000000000:
raise ValueError('out of range')
bit_pattern = struct.pack('Q', m | sign_bit)
return struct.unpack('d', bit_pattern)[0]
I added a default value to the second parameter so that you can used it in both cases, with or without offset x.

Calculating catalan numbers with memoization [duplicate]

This question already has answers here:
calculating catalan numbers using memoization
(2 answers)
Closed 7 years ago.
I am trying to use memoization in order to calculate catalan numbers, but it just does not seem to work, what do I need to change?
def catalan_mem(n, mem = None):
if n==0:
return 1
if mem==None:
mem={}
sum=0
if n not in mem:
for i in range(0, n):
sum = sum + catalan_mem(i) * catalan_mem(n-i-1)
mem[n]=sum
return mem[n]
You need to pass the cache to your recursive calls:
sum = sum + catalan_mem(i, mem) * catalan_mem(n-i-1, mem)
Otherwise, every method call creates a new empty cache.

Calculating exp(x) with the use of recursion in Python [duplicate]

This question already has answers here:
Why does the division get rounded to an integer? [duplicate]
(13 answers)
Closed 7 years ago.
I'm attempting to calculate e^x using recursion, e^x = e^(x/2)*e^(x/2), and the third order Maclaurin expansion for e^x and the script keeps returning 1. I'm not looking for a higher accuracy solution, just simply to understand where the script goes wrong : )
My thought is that with enough iterations it should end up with (1+x/N+(x/N)^2/2)^N when the function value goes below the limit.
def exp(x):
if abs(x)<0.0001:
return 1+x+x**2/2
else:
y=exp(x/2)
return y*y
Try this instead (note the 2.0 in the recursive call):
def exp(x):
if abs(x) < 0.0001:
return 1 + x + x**2 / 2.0
else:
y = exp(x / 2.0)
return y * y
It is failing because if you pass an integer in for x, say 1, then x / 2 does integer division (in python 2.x), which would result in 0 instead of 0.5. By using x / 2.0, it forces python to use float division.
def exp(x):
if abs(x)<0.0001:
return 1+x+(x**2)/2.0
else:
y=exp(x/2.0)
return y*y
Integer division truncates. You need floats here.

Computing PI in Python 2, how to stop answer truncating [duplicate]

This question already has answers here:
How to define a decimal class holding 1000 digits in python?
(4 answers)
Closed 7 years ago.
please go easy on me, I've been learning Python about a week!
I thought I'd try calculating Pi using the Rumanujan formula. I am confident I was able to code that correctly.
My answer is truncating and I'd like it to be represented with 200 dp. In C I'd use malloc to do this perhaps but I understand that Python doesn't work that way.
The learning point I'd like to take away from this is: Is the truncation caused by the limit of representing a float, and if so is it possible to fix?
Thanks.
import math
from decimal import *
getcontext().prec = 200
def iterate(n):
sum = 0
Decimal(sum)
sum = (math.factorial(4*n))
sum = (sum/math.pow(math.factorial(n), 4))
sum = sum*((26390*n +1103)/math.pow(396, (4*n)))
return sum
ans=0
Decimal(ans)
print "Choose the number of iterations:\n"
itnum = int(raw_input())
for n in range (0, itnum+1):
this_iteration = 0
Decimal(this_iteration)
this_iteration = iterate(n)
ans = ans + this_iteration
ans = ans*(math.pow(8, 0.5)/9801)
ans = 1/ans
print "%.200f" % ans
Your snippet
sum = 0
Decimal(sum)
leaves sum set to the int 0, and computes and throws away a Decimal equivalent. Use, instead, an assignment statement:
sum = Decimal(0)
Next, you'll need to ensure every intermediate result is also converted appropriately to Decimal (and floats by default are not).
Personally, I'd recommend using gmpy2 instead, but then, I'm biased:-).

Categories

Resources