I want to find all bases and exponents of a number.
Example:
Number = 64
2^6=64
4^3=64
8^2=64
64^1=64
Number = 1845.28125
4.5^5=1845.28125
Number = 19683
3^9=19683
27^3=19683
19683^1=19683
What I do now is to make an integer of 'Number' and just see of the results of multiple calculations gives the correct result:
basehits, expohits = [], []
if eval(Number) > 1000:
to = 1000 #base max 1000 in order to avoid too many calculations
else:
to = int(eval(Number))
for n in range(1,to):
for s in range(1,31): #just try with exponents from 1 to 30
calcres = pow(n,s)
if calcres == eval(Number):
basehits.append(n)
expohits.append(s)
elif calcres > eval(Number):
break
The problem is that this never find a Floating Number as for example 1845.28125 (see above).
Is there a better way to find exponents and bases when only the result is known?
Your problem needs more constraints, but here's some help:
>>> from math import log
>>> help(log)
Help on built-in function log in module math:
log(...)
log(x[, base])
Return the logarithm of x to the given base.
If the base not specified, returns the natural logarithm (base e) of x.
>>> for base in range(2, 10):
... exp = log(64, base)
... print('%s ^ %s = %s' % (base, exp, base ** exp))
...
2 ^ 6.0 = 64.0
3 ^ 3.785578521428744 = 63.99999999999994
4 ^ 3.0 = 64.0
5 ^ 2.5840593484403582 = 63.99999999999999
6 ^ 2.3211168434072493 = 63.99999999999998
7 ^ 2.1372431226481328 = 63.999999999999964
8 ^ 2.0 = 64.0
9 ^ 1.892789260714372 = 63.99999999999994
how about
import math
num=64
for i in range(2,int(math.sqrt(num))+1):
if math.log(num,i).is_integer():
print i,int(math.log(num,i))
the output is:
2 6
4 3
8 2
and of course, you can always add:
print num,1
to get
64,1
If you want to add fractions, with n decimal digits after the dot, you can use this:
from __future__ import division
import math
num=1845.28125
decimal_digits=1
ans=3
x=1
while(ans>=2):
ans=num**(1/x)
if (ans*10**decimal_digits).is_integer():
print ans,x
x+=1
where decimal_digits indicates the number of places after the dot.
For this example the answer will be
4.5 5,
If you change for example num to 39.0625 and decimal_digits to 2, the output will be:
2.5 4
6.25 2
Integers
For integers you could look at the prime factors of your number. Once you know that 64 is 2**6, it's easy to list all the results you wanted.
Now, which result do you expect for numbers that have at least 2 different prime factors? For example : should 15 be written 3*5, 3**1 * 5**1 or 15**1?
Floats
It's not clear how your problem is defined for Floats.
What's special about 4.5?
If you calculate 1845.28125**(1.0/5), Python returns 4.5, but for other input numbers, the result might be off by 1e-16.
Possible solution
import math
def find_possible_bases(num, min_base = 1.9, max_decimals = 9, max_diff = 1e-15):
max_exponent = int(math.ceil(math.log(num,min_base)))
for exp in range(1,max_exponent):
base = round(num**(1.0/exp),max_decimals)
diff = abs(base**exp-num)
if diff < max_diff:
print('%.10g ** %d = %.10g' % (base, exp, base ** exp))
find_possible_bases(64)
# 64 ** 1 = 64
# 8 ** 2 = 64
# 4 ** 3 = 64
# 2 ** 6 = 64
find_possible_bases(19683)
# 19683 ** 1 = 19683
# 27 ** 3 = 19683
# 3 ** 9 = 19683
find_possible_bases(1845.28125)
# 1845.28 ** 1 = 1845.28
# 4.5 ** 5 = 1845.28
find_possible_bases(15)
# 15 ** 1 = 15
It iterates over possible exponents, and calculates what the base would be. It rounds it to 9 decimals, and checks what the error becomes. If it's small enough, it displays the result. You could play with the parameters and find what best suits your problem.
As a bonus, it also works fine with Integers (e.g. 64 and 15).
It might be better to work with Rational numbers.
Related
I have a beginner problem. How can I round up to 2 decimal?
Here is what I tried and what I want to achieve:
import math
var_1 = 14.063 # expected = 14.06
var_2 = 10.625 # expected = 10.63
print(round(14.063, 2))
print(round(10.625, 2))
print('===========================')
def round_up(n, decimals=0):
multiplier = 10 ** decimals
return math.ceil(n * multiplier) / multiplier
print(round_up(var_1, 2))
print(round_up(var_2, 2))
And the Output is:
14.06
10.62
===========================
14.07
10.63
So neither of those wroks for me...
The Decimal class, quantize() method, and ROUND_HALF_UP rule from the decimal module can handle this:
from decimal import Decimal, ROUND_HALF_UP
var_1 = 14.063 # expected = 14.06
var_2 = 10.625 # expected = 10.63
# a Decimal object with an explicit exponent attribute/property (to be interpreted by quantize)
Two_places = Decimal("1e-2")
for var in [var_1, var_2]:
rounded = Decimal(var).quantize(Two_places, rounding=ROUND_HALF_UP)
print(f"decimal: {rounded}")
print(f"float: {float(rounded)}")
and I get:
decimal: 14.06
float: 14.06
decimal: 10.63
float: 10.63
Keep in mind that when you're dealing with floats, you're always manipulating a less-than-precise representation of what you probably (naturally) have in mind:
Decimal(1.65) # Decimal('1.649999999999999911182158029987476766109466552734375')
Decimal('1.65') # Decimal('1.65')
In the first case, 1.65 was first turned into an IEEE-754 float, which has precision errors going from base-10 to base-2, then passed to Decimal. In the second case, Decimal interpreted the number as "one, and 65 100-ths" which equates to "165 times 10 raised to the minus 2", or 165e-2.
Try this. This finds the nearest one and if not, then round up -
import math
v1 = 14.063
v2 = 10.625
def round_up(n, decimals=0):
multiplier = 10 ** decimals
var_down = round(n, 2)
var_up = math.ceil(n * multiplier) / multiplier
if n - var_down >= var_up - n:
return var_up
else:
return var_down
v1_round = round_up(v1, 2)
v2_round = round_up(v2, 2)
print (v1_round) # 14.06
print (v2_round) # 10.63
this should work, although there is probebly a more efficient way of doing it. I just took your code and determined which one was closer, and if they are the same to round up.
Edit: It seems that PCM has made such version.
import math
decimals = 2
var_1 = 14.063
var_2 = 10.625
var_1down = round(var_1, decimals)
var_2down = round(var_2, decimals)
def round_up(n, decimals=0):
multiplier = 10 ** decimals
return math.ceil(n * multiplier) / multiplier
var_1up = round_up(var_1, decimals)
var_2up = round_up(var_2, decimals)
if var_1 - var_1down >= var_1up - var_1:
var_1round = var_1up
else:
var_1round = var_1down
if var_2 - var_2down >= var_2up - var_2:
var_2round = var_2up
else:
var_2round = var_2down
print (var_1round)
print (var_2round)
If you check the docs you will see that "values are rounded to the closest multiple of 10 to the power minus ndigits; if two multiples are equally close, rounding is done toward the even choice (so, for example, both round(0.5) and round(-0.5) are 0, and round(1.5) is 2)".
So 10.625 rounds to 10.62. You may try adding a very small value, e.g. 0.00001, but even so, since the way float numbers work, you may have some surprise in a few cases.
I want to use str.format to convert 2 number to scientific notation raised to the same exponential but the exponential need to be set off the str.format.
Example:
from math import log10
y=10000
x=round(np.log10(y))
m=10
y="{:e}".format(y)
m="{:e}".format(m)
print(y)
print(m)
here I have that m has e = 1 and y e = 4 and what I want is for both to have the same "e". i want to set both to exponencial x.
I think you have to calculate this yourself, for example using a helper function which returns a string:
def format_exp(x, n):
significand = x / 10 ** n
exp_sign = '+' if n >= 0 else '-'
return f'{significand:f}e{exp_sign}{n:02d}'
Explanation:
x is the number to format, and n is the power that you want to display;
significand calculates the part to show in front of the e by dividing x by 10n (10 ** n);
exp_sign is either + or -, depending on the value of n (to replicate the default behaviour).
Example usage:
>>> import math
>>> y = 10000
>>> m = 10
>>> x = math.floor(math.log10(y)) # x = 4
>>> print(format_exp(y, x))
1.000000e+04
>>> print(format_exp(m, x))
0.001000e+04
>>> print(format_exp(y, 1))
1000.000000e+01
>>> print(format_exp(m, 1))
1.000000e+01
You can increase the complexity of this function by adding an additional parameter d to set the number of decimals printed in the significand part (with a default value of 6 to reproduce the default Python behaviour):
def format_exp(x, n, d=6):
significand = x / 10 ** n
exp_sign = '+' if n >= 0 else '-'
return f'{significand:.{d}f}e{exp_sign}{n:02d}'
With this function, you can control the number of decimals printed:
>>> print(format_exp(y, x)) # default behaviour still works
1.000000e+04
>>> print(format_exp(y, x, 4))
1.0000e+04
>>> print(format_exp(y, x, 1))
1.0e+04
We have a partially working code and 2 examples with different types of custom steps. The example 2 (Int) is working, while the example 1 is not, as it is rounding up instead of down.
import math
def step_size_to_precision(ss):
return ss.find('1') - 1
def format_value(val, step_size_str):
precision = step_size_to_precision(step_size_str)
if precision > 0:
return "{:0.0{}f}".format(val, precision)
return math.floor(int(val))
###########################
# # example 1
step_size = "0.00000100"
quantity = 0.00725562
print(quantity)
print(format_value(quantity, step_size))
# 0.00725562
# 0.007256 <= Is rounding up instead of down. Should be 0.007255
###########################
# # example 2
# step_size = "1"
# quantity = 3.00725562
# print(quantity)
# print(format_value(quantity, step_size))
# returns 3 <= This is correct
###########################
How do we fix it?
You'll want to use Decimal objects to for precise decimal numbers to begin with.
Then, use Decimal.quantize() in the ROUND_DOWN mode.
from decimal import Decimal, ROUND_DOWN
quantity = 0.00725562
step_size = Decimal("0.000001")
print(Decimal(quantity).quantize(step_size, ROUND_DOWN))
prints out
0.007255
Another approach is outlined in this SO answer:
If you want to round down always (instead of rounding to the nearest
precision), then do so, explicitly, with the math.floor()
function:
from math import floor
def floored_percentage(val, digits):
val *= 10 ** (digits + 2)
return '{1:.{0}f}%'.format(digits, floor(val) / 10 ** digits)
print floored_percentage(0.995, 1)
Demo:
>>> from math import floor
>>> def floored_percentage(val, digits):
... val *= 10 ** (digits + 2)
... return '{1:.{0}f}%'.format(digits, floor(val) / 10 ** digits)
...
>>> floored_percentage(0.995, 1)
'99.5%'
>>> floored_percentage(0.995, 2)
'99.50%'
>>> floored_percentage(0.99987, 2)
'99.98%'
For your example:
import math
def step_size_to_precision(ss):
return max(ss.find('1'), 1) - 1
def format_value(val, step_size):
digits = step_size_to_precision(step_size)
val *= 10 ** digits
return '{1:.{0}f}'.format(digits, math.floor(val) / 10 ** digits)
step_size = "0.00000100"
quantity = 0.00725562
print(quantity)
print(format_value(quantity, step_size))
# prints out: 0.007255
A more general approach which allows to round down for step_size which is not only power of 10:
from decimal import Decimal
def floor_step_size(quantity, step_size):
step_size_dec = Decimal(str(step_size))
return float(int(Decimal(str(quantity)) / step_size_dec) * step_size_dec)
Usage:
>>> floor_step_size(0.00725562, "0.00000100")
0.007255
>>> floor_step_size(3.00725562, "1")
3.0
>>> floor_step_size(2.6, "0.25")
2.5
>>> floor_step_size(0.9, "0.2")
0.8
For my school project I was trying to compute the value of using different methods. One of the formula I found was the Machin Formula that can be calculated using the Taylor expansion of arctan(x).
I wrote the following code in python:
import decimal
count = pi = a = b = c = d = val1 = val2 = decimal.Decimal(0) #Initializing the variables
decimal.getcontext().prec = 25 #Setting percision
while (decimal.Decimal(count) <= decimal.Decimal(100)):
a = pow(decimal.Decimal(-1), decimal.Decimal(count))
b = ((decimal.Decimal(2) * decimal.Decimal(count)) + decimal.Decimal(1))
c = pow(decimal.Decimal(1/5), decimal.Decimal(b))
d = (decimal.Decimal(a) / decimal.Decimal(b)) * decimal.Decimal(c)
val1 = decimal.Decimal(val1) + decimal.Decimal(d)
count = decimal.Decimal(count) + decimal.Decimal(1)
#The series has been divided into multiple small parts to reduce confusion
count = a = b = c = d = decimal.Decimal(0) #Resetting the variables
while (decimal.Decimal(count) <= decimal.Decimal(10)):
a = pow(decimal.Decimal(-1), decimal.Decimal(count))
b = ((decimal.Decimal(2) * decimal.Decimal(count)) + decimal.Decimal(1))
c = pow(decimal.Decimal(1/239), decimal.Decimal(b))
d = (decimal.Decimal(a) / decimal.Decimal(b)) * decimal.Decimal(c)
val2 = decimal.Decimal(val2) + decimal.Decimal(d)
count = decimal.Decimal(count) + decimal.Decimal(1)
#The series has been divided into multiple small parts to reduce confusion
pi = (decimal.Decimal(16) * decimal.Decimal(val1)) - (decimal.Decimal(4) * decimal.Decimal(val2))
print(pi)
The problem is that I am getting the right value of pi only till 15 decimal places, no matter the number of times the loop repeats itself.
For example:
at 11 repetitions of the first loop
pi = 3.141592653589793408632493
at 100 repetitions of the first loop
pi = 3.141592653589793410703296
I am not increasing the repetitions of the second loop as arctan(1/239) is very small and reaches an extremely small value with a few repetitions and therefore should not affect the value of pi at only 15 decimal places.
EXTRA INFORMATION:
The Machin Formula states that:
π = (16 * Summation of (((-1)^n) / 2n+1) * ((1/5)^(2n+1))) - (4 * Summation of (((-1)^n) / 2n+1) * ((1/239)^(2n+1)))
That many terms is enough to get you over 50 decimal places. The problem is that you are mixing Python floats with Decimals, so your calculations are polluted with the errors in those floats, which are only precise to 53 bits (around 15 decimal digits).
You can fix that by changing
c = pow(decimal.Decimal(1/5), decimal.Decimal(b))
to
c = pow(1 / decimal.Decimal(5), decimal.Decimal(b))
or
c = pow(decimal.Decimal(5), decimal.Decimal(-b))
Obviously, a similar change needs to be made to
c = pow(decimal.Decimal(1/239), decimal.Decimal(b))
You could make your code a lot more readable. For starters, you should put the stuff that calculates the arctan series into a function, rather than duplicating it for arctan(1/5) and arctan(1/239).
Also, you don't need to use Decimal for everything. You can just use simple Python integers for things like count and a. Eg, your calculation for a can be written as
a = (-1) ** count
or you could just set a to 1 outside the loop and negate it each time through the loop.
Here's a more compact version of your code.
import decimal
decimal.getcontext().prec = 60 #Setting precision
def arccot(n, terms):
base = 1 / decimal.Decimal(n)
result = 0
sign = 1
for b in range(1, 2*terms, 2):
result += sign * (base ** b) / b
sign = -sign
return result
pi = 16 * arccot(5, 50) - 4 * arccot(239, 11)
print(pi)
output
3.14159265358979323846264338327950288419716939937510582094048
The last 4 digits are rubbish, but the rest are fine.
>>> a = 0.3135
>>> print("%.3f" % a)
0.314
>>> a = 0.3125
>>> print("%.3f" % a)
0.312
>>>
I am expecting 0.313 instead of 0.312
Any thought on why is this, and is there alternative way I can use to get 0.313?
Thanks
Python 3 rounds according to the IEEE 754 standard, using a round-to-even approach.
If you want to round in a different way then simply implement it by hand:
import math
def my_round(n, ndigits):
part = n * 10 ** ndigits
delta = part - int(part)
# always round "away from 0"
if delta >= 0.5 or -0.5 < delta <= 0:
part = math.ceil(part)
else:
part = math.floor(part)
return part / (10 ** ndigits) if ndigits >= 0 else part * 10 ** abs(ndigits)
Example usage:
In [12]: my_round(0.3125, 3)
Out[12]: 0.313
Note: in python2 rounding is always away from zero, while in python3 it rounds to even. (see, for example, the difference in the documentation for the round function between 2.7 and 3.3).
If you need accuracy don't use float, use Decimal
>>> from decimal import *
>>> d = Decimal(0.3125)
>>> getcontext().rounding = ROUND_UP
>>> round(d, 3)
Decimal('0.313')
or even Fraction
try
print '%.3f' % round(.3125,3)
I had the same incorrect rounding
round(0.573175, 5) = 0.57317
My solution
def to_round(val, precision=5):
prec = 10 ** precision
return str(round(val * prec) / prec)
to_round(0.573175) = '0.57318'