Round a number up to certain significant figures - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Round a number up to certain significant figures (/thread-2747.html) |
Round a number up to certain significant figures - brocq_18 - Apr-06-2017 import math maxValue = 12345678 a = maxValue/4.0 # Python 2.x requires either numerator/denominator to be a float to return one print "This is the value of a", a print "This is the ceiling of the division", math.ceil(a) This is the value of a 3086419.5 This is the ceiling of the division 3086420.0How can I amend the degree to which the value is rounded up? Is it possible to round up to say 3090000.0? RE: Round a number up to certain significant figures - snippsat - Apr-06-2017 import math maxValue = 12345678 a = maxValue / 4.0 print("This is the value of a: {}".format(a)) n = int(round(math.ceil(a), -4)) print("This is the ceiling of the division: {}".format(n))
RE: Round a number up to certain significant figures - Ofnuts - Apr-06-2017 To round to nearest N: * add N/2 * integer-divide by N * multiply by N def round(x,N): return ( (x+N/2) // N) * N RE: Round a number up to certain significant figures - brocq_18 - Apr-06-2017 import math maxValue = 123 # maximum value a = maxValue/4.0 # Python 2.x requires either numerator/denominator to be a float to return one integerPart = str(a).split('.')[0] # if "a" is a decimal this selects the integer part numberDigits = len(integerPart) # length of integerPart def upperRound(x,N): return ((x+N/2) // N) * N print "Maximum value = {}".format(maxValue) print "Maximum value/4 = {}".format(a) print "length of integer part = {}".format(numberDigits) print upperRound(a, 10-numberDigits) Maybe this is more of a mathematical question than Python. How can I amend the 2nd argument in upperRound such that the value returned from it for maxValue=1234 is bigger than Maximum value/4=308.5, as is the result if applied in this situation? Basically I want this script to be fully automated other than the maxValue being input by human, so for any maxValue/4, the output from upperRound should be bigger. RE: Round a number up to certain significant figures - alicarlos13 - Apr-06-2017 (Apr-06-2017, 06:13 PM)brocq_18 Wrote: Maybe this is more of a mathematical question than Python. How can I amend the 2nd argument in upperRound such that the value returned from it for maxValue=1234 is bigger than Maximum value/4=308.5, as is the result if applied in this situation? What you know have in the code is awkward, in the upperRound. I would just use print math.ceil(a) |