为什么我的程序可以使用大于一的数字

时间:2019-07-12 08:09:43

标签: python

我只是出于娱乐目的而做自己的事情,所以我决定尝试使程序找到重复出现的小数部分。我已经对该程序进行了很多尝试,并使其能够一直工作,直到达到大于1的数字为止。

whole = number // 1
number -= whole
repeating = ''
final_repeating = ''
copy_of_number = str(number)
stop = False

number = str(number)[2:]
for digit in number:
    repeating += digit
    number = number[1:]
    for checker in range(len(repeating)):
        try:
            if repeating[checker] == number[0]:
                final_repeating = repeating[checker:]
                times_it_appears = number.count(final_repeating)
                length = len(number)
                length_of_final = len(final_repeating)
                if times_it_appears == length // length_of_final and (length % length_of_final == 0 or number[(length % length_of_final * -1):] == final_repeating[:(length % length_of_final)]):
                    stop = True
                    break
                else:
                    final_repeating = ''
        except IndexError:
            print('this isn\'t a reoccuring decimal')
            quit()
    if stop == True:
        break

如果数字= 1.166666或其他任何大于等于2的6,则其final_repeating应该等于'6'并且代码应继续进行

实际输出是它不是重复出现的小数,并且如果我检查数字。程序完成后,用户没有键入

,最后有很多0和一个随机的单个数字。

2 个答案:

答案 0 :(得分:0)

我编写了一个程序,可以将给定有理数的“任意”转换为分数。

我构建了一个函数,该函数接收表示有理数的字符串,例如"2.5(37)""-7.8""4",并返回包含相应分数的字符串。

例如:from_string_to_fraction("-2.5(37)")返回"-1256/495"。它需要功能gcdnumber_decimal_places

这仅适用于有理数,因为有理数是所有数字,并且是唯一可写为整数的除数的数字,即整数的定义。请注意,重复出现的小数(dízimasinfinitasperiódicas)是有理数,并且0,(9)= 1。

def gcd(a=1,b=1):
  """Returns the greatest common divisor between two positive integers."""
  if b==0:
    return a 
  else: 
    return gcd(b,a%b)

def number_decimal_places(x=0):
  """Returns the number of decimal places of a float."""
  if x==int(x):
    return 0
  return len(str(x)[str(x).index('.')+1:])

def from_string_to_fraction(x='0'):
  """Receives a string representing a rational number such as "2.5(37)", "-7.8" or "4"  
     and returns a string with the correspondent fraction. 
     Eg.: from_string_to_fraction("-2.5(37)") returns "-1256/495". 
     It needs the functions gcd and number_decimal_places! Make sure the argument is valid!"""

  x=x.replace(',','.',1) # for the program to work with a ',' separating the integer and decimal part

  sign=1 
  if x[0]=='-': # if x is negative, this turns x into a positive number and, 
                # in the end, we turn the final result into positive again by making "final_result*=sign"
    sign=-1
    x=x[1:]

  ################  GETTING THE FINIT PART AND THE PERIOD  ###########################

  # I will explain this with an example:
  # if x= "2.5(37)"; then I set f, the finit part, to 2.5 and p, the period to 37
  # if the number is non-reccuring, f=x since it has no period
  # Note: x, our argument, is still a 'string'

  try: # this will be executed iff x is a non-reoccurring decimal:
    f=x=eval(x)  #IF YOU WANT THIS TO WORK ONLY WITH REOCCURRING DECIMALS MAKE THE PROGRAM RETURN IN THIS LINE
    p=0 # set the period of the number to 0
  except TypeError: # this will be executed iff x is a reoccurring decimal:
    f=float(x[:x.index('(')]) # finit part of the dizim  # all the way until '('
    p=int(x[x.index('(')+1:x.index(')')]) # period of the dizim  # the part of the number between '(' and ')')

  ########################  GET THE NUMERATOR AND DENOMINATOR   #######################

  # Then, with f and p defined, I have to discover the numerator and the denominator:

  # if y=2,5(37):   # here is a method that can be used in paper to discover the fraction:
  # 1000y - y = 2537,(37) - 25,(37)
  # <=> y = ( 2537,(37)-25,(37) )    /     (1000-1)
  # <=> y =      (2537-25)           /     (1000-1)
  # <=> y =      numerator           /    denominator
  #       both numerator and denominator are int's          

  # I implemented this with f and p:

  numerator=f*10**(number_decimal_places(f)+len(str(p)))+p  -  f*10**number_decimal_places(f) # =25 from the eg. # (=2537-25 from the Eg.)

  denominator=10**(number_decimal_places(f)+len(str(p)))  -  10**number_decimal_places(f) # =1 from the eg. # (=1000-1 from the Eg.)

  #######################  SIMPLIFYING THE FRACTION   ###################################
  # Here I am slimplifying the fraction, if it is possible:

  factor=gcd(numerator,denominator)

  numerator=sign*(numerator/factor)
  denominator=denominator/factor

  return "%d/%d" % (numerator,denominator)

#TESTING
print("This program turns a rational number into a fraction, for example: -2.5(37)=-2.53737373737373737...=-1256/495)
try:
  x=input("Enter \"any\" rational number: ")
  print("%s = %s" % (x,from_string_to_fraction(x)))
except:
  print("Error :(")

很抱歉,如果没有帮助,将来可能会帮助其他人。

这个答案花了我很多时间,我希望将来有人会用它来将“ dizim”表示形式的有理数转换为分数。

程序似乎有点大,但这是由于注释所致。

答案 1 :(得分:0)

当您从数字中减去整数时,Python会近似结果。从数字中减去整数时,可以舍入数字以避免这种情况。

用以下代码替换代码的前两行:

copy_of_number=str(number)
whole = int(number // 1)
copy_of_whole=str(whole)
number -= whole
number = round(number, len(copy_of_number)-len(copy_of_whole)-1)