如何知道一个数的所有基和指数?

2024-04-19 11:53:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我想找出一个数的所有基和指数。你知道吗

示例:

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

我现在要做的是把‘Number’变成一个整数,只要看多次计算的结果,就会得到正确的结果:

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

问题是它永远找不到浮点数,例如1845.28125(见上文)。
只有结果是已知的,有没有更好的方法来求指数和基呢?你知道吗


Tags: toin示例numberforbaseifeval
3条回答

你的问题需要更多的约束,但这里有一些帮助:

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

整数

对于整数,您可以查看数字的prime factors。一旦您知道64是2**6,就很容易列出您想要的所有结果。你知道吗

现在,对于至少有两个不同素数因子的数,你期望得到哪个结果?例如:15应该是3*53**1 * 5**1还是15**1写的?你知道吗

浮动

不清楚你的问题是如何定义为浮动的。你知道吗

4.5有什么特别之处? 如果计算1845.28125**(1.0/5),Python返回4.5,但是对于其他输入数字,结果可能会被1e-16关闭。你知道吗

可能的解决方案

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

它迭代可能的指数,并计算基数。它将其舍入到9位小数,并检查错误是什么。如果足够小,则显示结果。你可以利用这些参数,找出最适合你的问题。 另外,它还可以处理整数(例如64和15)。你知道吗

最好使用Rational numbers。你知道吗

怎么样

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))

输出为:

2 6
4 3
8 2

当然,你也可以加上:

print num,1 

得到

64,1

如果要添加小数点后有n位小数的分数,可以使用以下方法:

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

其中decimal_digits表示点后面的位数。你知道吗

对于这个例子,答案是

4.5 5

例如,如果将num更改为39.0625decimal_digits更改为2,则输出将为:

2.5 4 6.25 2

相关问题 更多 >