I am trying to solve this excercise:
https://projecteuler.net/problem=16
The code is pretty self-explanatory: I calculate 2^n in power(n), and in sum(n), I cut off the last digit of the number. I do this as long as pow > 0. I receive the right solution for 2^15, but for one reason or another, the same code doesn't work for 2^1000. I receive 1889, which is apparently wrong.
def power(n):
power = 2
for x in range(1, n):
power = 2*power
return power
def sum(n):
pow = power(n)
sum = 0
while pow > 0:
modulo = pow%10
sum = sum + modulo
pow = int((pow - modulo)/10)
return sum
def main():
print(int(sum(1000)))
if __name__ == '__main__':
main()
A simple change in your code will give you the correct answer,
def power(n):
power = 2
for x in range(1, n):
power = 2*power
return power
def sum(n):
pow = power(n)
sum = 0
while pow > 0:
modulo = pow%10
sum = sum + modulo
pow = pow//10 # modified line
return sum
def main():
print(int(sum(1000)))
if __name__ == '__main__':
main()
The reason why your example doesn't work is because you are casting the result of a float operation to int. Floats are never precise and when they are very large, they loose precision. Hence if you convert them back to integer, you get a much lower value.
A better function using divmod() is,
def sum(n):
pow = power(n)
sum = 0
while pow > 0:
pow,modulo = divmod(pow,10)
sum = sum + modulo
return sum
Your original solution would have worked in Python 2 because Python 2 and Python 3 handle division differently.
For example print(1/2) gives 0 in Python2, and 0.5 in Python3. In Python3, we use // for floor division (which is what you want here).
Your code doesn't work for any number >= 57
The problem here is very easy to solve.
In python 3 and higher, / is a division that returns a float, while // is an integer division that always returns an integer. Since you are using float division, you are encountering the issues with floating point arithmetic.
More about the issues and limitations.
To solve your problem, change the line
pow = int(pow - modulo)/10
into
pow = int(pow - modulo)//10
or even better, you can just say pow//=10
Isn't python beatiful?
def Power_digit_sum(n):
number = list(str(2**n)) # pow number and convert number in string and list
result= [int(i) for i in number]# convert number in int and
return sum(result) # sum list
print(Power_digit_sum(15)) # result 26
print(Power_digit_sum(1000)) # result 1366
Related
I would like to design a function f(x : float, up : bool) with these input/output:
# 2 decimals part rounded up (up = True)
f(142.452, True) = 142.46
f(142.449, True) = 142.45
# 2 decimals part rounded down (up = False)
f(142.452, False) = 142.45
f(142.449, False) = 142.44
Now, I know about Python's round built-in function but it will always round 142.449 up, which is not what I want.
Is there a way to do this in a nicer pythonic way than to do a bunch of float comparisons with epsilons (prone to errors)?
Have you considered a mathematical approach using floor and ceil?
If you always want to round to 2 digits, then you could premultiply the number to be rounded by 100, then perform the rounding to the nearest integer and then divide again by 100.
from math import floor, ceil
def rounder(num, up=True):
digits = 2
mul = 10**digits
if up:
return ceil(num * mul)/mul
else:
return floor(num*mul)/mul
You can also perform some mathematical logic if you do not want to use any explicit function as:
def f(num, up):
num = num * 100
if up and num != int(num): # if up and "float' value != 'int' value
num += 1
return int(num) / (100.0)
Here, the idea is if up is True and int value of number is not equal to float value then increase the number by 1. Else it will be same as the original number
math.ceil() rounds up, and math.floor() rounds down. So, the following is an example of how to use it:
import math
def f(x, b):
if b:
return (math.ceil(100*x) / 100)
else:
return (math.floor(100*x) / 100)
This function should do exactly what you want.
Could someone help check why the result is always one and let me know what I did wrong? Thanks
Correct result should be: 1/1 + 1/2 + 1/3 == 1.83333333333.
x = int(input("Enter n: "))
assert x > 0, "n must be greater than zero!"
def one_over_n(x):
result = 0
for n in range(x):
n += 1
result += 1 / n
return result
r = one_over_n(x)
print("one_over_n( {0:d} ): {1:f}" .format(x, r))
It will work correctly on python 3, but not in python 2
>>> 1/2
0
That means you are just adding zeroes, to one. You will need to change either numerator or denominator to a float number e.g. 1/2.0, so change your code to
result += 1.0 / n
See Pep 238 to see why it was changed in python 3.
btw floating point numbers can't represent all fractions, so if you are just adding fractions, you can use Fraction class e.g.
>>> from fractions import Fraction as F
>>> F(1,1) + F(1,2) + F(1,3)
Fraction(11, 6)
As an alternative, to force Python 2 perform division as you expect (rather than integer division), add:
from __future__ import division
This seems to be simple but I cannot find a way to do it. I need to show whether the cube root of an integer is integer or not. I used is_integer() float method in Python 3.4 but that wasn't successful. As
x = (3**3)**(1/3.0)
is_integer(x)
True
but
x = (4**3)**(1/3.0)
is_integer(x)
False
I tried x%1 == 0,x == int(x) and isinstance(x,int) with no success.
I'd appreciate any comment.
For small numbers (<~1013 or so), you can use the following approach:
def is_perfect_cube(n):
c = int(n**(1/3.))
return (c**3 == n) or ((c+1)**3 == n)
This truncates the floating-point cuberoot, then tests the two nearest integers.
For larger numbers, one way to do it is to do a binary search for the true cube root using integers only to preserve precision:
def find_cube_root(n):
lo = 0
hi = 1 << ((n.bit_length() + 2) // 3)
while lo < hi:
mid = (lo+hi)//2
if mid**3 < n:
lo = mid+1
else:
hi = mid
return lo
def is_perfect_cube(n):
return find_cube_root(n)**3 == n
In SymPy there is also the integer_nthroot function which will quickly find the integer nth root of a number and tell you whether it was exact, too:
>>> integer_nthroot(primorial(12)+1,3)
(19505, False)
So your function could be
def is_perfect_cube(x): return integer_nthroot(x, 3)[1]
(And because SymPy is open source, you can look at the routine to see how integer_nthroot works.)
If your numbers aren't big, I would do:
def is_perfect_cube(number):
return number in [x**3 for x in range(15)]
Of course, 15 could be replaced with something more appropriate.
If you do need to deal with big numbers, I would use the sympy library to get more accurate results.
from sympy import S, Rational
def is_perfect_cube(number):
# change the number into a sympy object
num = S(number)
return (num**Rational(1,3)).is_Integer
To elaborate on the answer by #nneonneo, one could write a more general kth-root function to use instead of cube_root,
def kth_root(n,k):
lb,ub = 0,n #lower bound, upper bound
while lb < ub:
guess = (lb+ub)//2
if pow(guess,k) < n: lb = guess+1
else: ub = guess
return lb
def is_perfect_cube(n):
return kth_root(n,3) == n
This is another approach using the math module.
import math
num = int(input('Enter a number: '))
root = int(input('Enter a root: '))
nth_root = math.pow(num, (1/root))
nth_root = round(nth_root, 10)
print('\nThe {} root of {} is {}.'.format(root, num, nth_root))
decimal, whole = math.modf(nth_root)
print('The decimal portion of this cube root is {}.'.format(decimal))
decimal == 0
Line 1: Import math module.
Line 2: Enter the number you would like to get the root of.
Line 3: Enter the nth root you are looking for.
Line 4: Use the power function.
Line 5: Rounded to 10 significant figures to account for floating point approximations.
Line 6: Print a preview of the nth root of the selected number.
Line 7: Use the modf function to get the fractional and integer parts.
Line 8: Print a preview of decimal part of the cube root value.
Line 9: Return True if the cube root is an integer. Return False if the cube root value contains fractional numbers.
I think you should use the round function to get the answer. If I had to write a function then it will be as follows:
def cube_integer(n):
if round(n**(1.0/3.0))**3 == n:
return True
return False
You can use something similar to int(n**(1.0/3.0)) == n**(1.0/3.0), but in python because of some issues with the computation of the value of cube root, it is not exactly computed. For example int(41063625**(1.0/3.0)) will give you 344, but the value should be 345.
in Python 3.11 you can use math.cbrt
x = 64
math.cbrt(x).is_integer
(or)
or use numpy.cbrt
import numpy as np
x = 64
np.cbrt(x).is_integer
For calculating Catalan Numbers, I wrote two codes. One (def "Catalan") works recursively and returns the right Catalan Numbers.
dicatalan = {}
def catalan(n):
if n == 0:
return 1
else:
res = 0
if n not in dicatalan:
for i in range(n):
res += catalan(i) * catalan(n - i - 1)
dicatalan[n] = res
return dicatalan[n]
the other (def "catalanFormula") applies the implicit formula, but doesn't calculate accurately starting from n=30. the problem derives from floating points - for k=9 the program returns "6835971.999999999" instead of "6835972" and from this moment on accumulates mistakes till the final wrong answer.
(print line is for checking)
def catalanFormula(n):
result = 1
for k in range(2, n + 1):
result *= ((n + k) / k)
print (result)
return int(result)
I tried rounding and failed, tried Decimal import and still got nothing right.
I need the "catalanFormula" work perfectly as "catalan";
Any Ideas?
Thanks!
Try calculating the numerator and denominator separately and dividing them at the end. If you do this, you should be able to make it a little bit farther with floating-point.
I'm sure Python has a package for rational numbers. Using rationals is an even better idea.
See the bigfloat package.
from bigfloat import *
setcontext(quadruple_precision)
def catalanFormula(n):
result = BigFloat(1)
for k in range(2, n + 1):
result *= ((BigFloat(n) + BigFloat(k)) / BigFloat(k))
return result
catalanFormula(30)
Output:
BigFloat.exact('3814986502092304.00000000000000000043', precision=113)
In Python 3, I am checking whether a given value is triangular, that is, it can be represented as n * (n + 1) / 2 for some positive integer n.
Can I just write:
import math
def is_triangular1(x):
num = (1 / 2) * (math.sqrt(8 * x + 1) - 1)
return int(num) == num
Or do I need to do check within a tolerance instead?
epsilon = 0.000000000001
def is_triangular2(x):
num = (1 / 2) * (math.sqrt(8 * x + 1) - 1)
return abs(int(num) - num) < epsilon
I checked that both of the functions return same results for x up to 1,000,000. But I am not sure if generally speaking int(x) == x will always correctly determine whether a number is integer, because of the cases when for example 5 is represented as 4.99999999999997 etc.
As far as I know, the second way is the correct one if I do it in C, but I am not sure about Python 3.
There is is_integer function in python float type:
>>> float(1.0).is_integer()
True
>>> float(1.001).is_integer()
False
>>>
Both your implementations have problems. It actually can happen that you end up with something like 4.999999999999997, so using int() is not an option.
I'd go for a completely different approach: First assume that your number is triangular, and compute what n would be in that case. In that first step, you can round generously, since it's only necessary to get the result right if the number actually is triangular. Next, compute n * (n + 1) / 2 for this n, and compare the result to x. Now, you are comparing two integers, so there are no inaccuracies left.
The computation of n can be simplified by expanding
(1/2) * (math.sqrt(8*x+1)-1) = math.sqrt(2 * x + 0.25) - 0.5
and utilizing that
round(y - 0.5) = int(y)
for positive y.
def is_triangular(x):
n = int(math.sqrt(2 * x))
return x == n * (n + 1) / 2
You'll want to do the latter. In Programming in Python 3 the following example is given as the most accurate way to compare
def equal_float(a, b):
#return abs(a - b) <= sys.float_info.epsilon
return abs(a - b) <= chosen_value #see edit below for more info
Also, since epsilon is the "smallest difference the machine can distinguish between two floating-point numbers", you'll want to use <= in your function.
Edit: After reading the comments below I have looked back at the book and it specifically says "Here is a simple function for comparing floats for equality to the limit of the machines accuracy". I believe this was just an example for comparing floats to extreme precision but the fact that error is introduced with many float calculations this should rarely if ever be used. I characterized it as the "most accurate" way to compare in my answer, which in some sense is true, but rarely what is intended when comparing floats or integers to floats. Choosing a value (ex: 0.00000000001) based on the "problem domain" of the function instead of using sys.float_info.epsilon is the correct approach.
Thanks to S.Lott and Sven Marnach for their corrections, and I apologize if I led anyone down the wrong path.
Python does have a Decimal class (in the decimal module), which you could use to avoid the imprecision of floats.
floats can exactly represent all integers in their range - floating-point equality is only tricky if you care about the bit after the point. So, as long as all of the calculations in your formula return whole numbers for the cases you're interested in, int(num) == num is perfectly safe.
So, we need to prove that for any triangular number, every piece of maths you do can be done with integer arithmetic (and anything coming out as a non-integer must imply that x is not triangular):
To start with, we can assume that x must be an integer - this is required in the definition of 'triangular number'.
This being the case, 8*x + 1 will also be an integer, since the integers are closed under + and * .
math.sqrt() returns float; but if x is triangular, then the square root will be a whole number - ie, again exactly represented.
So, for all x that should return true in your functions, int(num) == num will be true, and so your istriangular1 will always work. The only sticking point, as mentioned in the comments to the question, is that Python 2 by default does integer division in the same way as C - int/int => int, truncating if the result can't be represented exactly as an int. So, 1/2 == 0. This is fixed in Python 3, or by having the line
from __future__ import division
near the top of your code.
I think the module decimal is what you need
You can round your number to e.g. 14 decimal places or less:
>>> round(4.999999999999997, 14)
5.0
PS: double precision is about 15 decimal places
It is hard to argue with standards.
In C99 and POSIX, the standard for rounding a float to an int is defined by nearbyint() The important concept is the direction of rounding and the locale specific rounding convention.
Assuming the convention is common rounding, this is the same as the C99 convention in Python:
#!/usr/bin/python
import math
infinity = math.ldexp(1.0, 1023) * 2
def nearbyint(x):
"""returns the nearest int as the C99 standard would"""
# handle NaN
if x!=x:
return x
if x >= infinity:
return infinity
if x <= -infinity:
return -infinity
if x==0.0:
return x
return math.floor(x + 0.5)
If you want more control over rounding, consider using the Decimal module and choose the rounding convention you wish to employ. You may want to use Banker's Rounding for example.
Once you have decided on the convention, round to an int and compare to the other int.
Consider using NumPy, they take care of everything under the hood.
import numpy as np
result_bool = np.isclose(float1, float2)
Python has unlimited integer precision, but only 53 bits of float precision. When you square a number, you double the number of bits it requires. This means that the ULP of the original number is (approximately) twice the ULP of the square root.
You start running into issues with numbers around 50 bits or so, because the difference between the fractional representation of an irrational root and the nearest integer can be smaller than the ULP. Even in this case, checking if you are within tolerance will do more harm than good (by increasing the number of false positives).
For example:
>>> x = (1 << 26) - 1
>>> (math.sqrt(x**2)).is_integer()
True
>>> (math.sqrt(x**2 + 1)).is_integer()
False
>>> (math.sqrt(x**2 - 1)).is_integer()
False
>>> y = (1 << 27) - 1
>>> (math.sqrt(y**2)).is_integer()
True
>>> (math.sqrt(y**2 + 1)).is_integer()
True
>>> (math.sqrt(y**2 - 1)).is_integer()
True
>>> (math.sqrt(y**2 + 2)).is_integer()
False
>>> (math.sqrt(y**2 - 2)).is_integer()
True
>>> (math.sqrt(y**2 - 3)).is_integer()
False
You can therefore rework the formulation of your problem slightly. If an integer x is a triangular number, there exists an integer n such that x = n * (n + 1) // 2. The resulting quadratic is n**2 + n - 2 * x = 0. All you need to know is if the discriminant 1 + 8 * x is a perfect square. You can compute the integer square root of an integer using math.isqrt starting with python 3.8. Prior to that, you could use one of the algorithms from Wikipedia, implemented on SO here.
You can therefore stay entirely in python's infinite-precision integer domain with the following one-liner:
def is_triangular(x):
return math.isqrt(k := 8 * x + 1)**2 == k
Now you can do something like this:
>>> x = 58686775177009424410876674976531835606028390913650409380075
>>> math.isqrt(k := 8 * x + 1)**2 == k
True
>>> math.isqrt(k := 8 * (x + 1) + 1)**2 == k
False
>>> math.sqrt(k := 8 * x + 1)**2 == k
False
The first result is correct: x in this example is a triangular number computed with n = 342598234604352345342958762349.
Python still uses the same floating point representation and operations C does, so the second one is the correct way.
Under the hood, Python's float type is a C double.
The most robust way would be to get the nearest integer to num, then test if that integers satisfies the property you're after:
import math
def is_triangular1(x):
num = (1/2) * (math.sqrt(8*x+1)-1 )
inum = int(round(num))
return inum*(inum+1) == 2*x # This line uses only integer arithmetic