-5

The prompt we were initially given says to create a function that receives a number as an argument and returns the log of that number rounded to 4 decimals places. I need the function to take the min_num and max_num as the arguments

This is my code:

def min_num():
    while True:
        i = int(input("What's your minimum value?"))
        if i > 0:
            return i
        print("ERROR. Minimum should be greater than 0")


def max_num(min_mum):
    while True:
        i = int(input("What's your maximum value?"))
        if i > min_num:
            return i 
        print(f"ERROR. Maximum value must be greater {min})")

 min_value = min_num()
 max_value = max_num(min_value)
blues
  • 4,547
  • 3
  • 23
  • 39
  • Where are you stuck exactly? Is this a [homework question](https://softwareengineering.meta.stackexchange.com/questions/6166/open-letter-to-students-with-homework-problems)? – jrbergen Feb 15 '22 at 03:35
  • It is a homework question. I need to figure out how to use the log function. Could I, for example, say def log(min) return log. But it needs to be rounded to 4 decimal places – Kayla Williams Feb 15 '22 at 03:40
  • 1
    Have you been able to write a function that returns the log of a number without the rounding? If so, please include that in your question. If not, you might want to go back and review earlier assignments (you'll need to understand how to `import` and how to call functions from imported modules). – Samwise Feb 15 '22 at 18:26

2 Answers2

2

You could use the log function that comes with Python's math package.

The built-in round function takes the number of decimals to round to as the second argument. round is more prone to inaccuracies than is Decimal sugggested by @alexpdev's, but I suppose that is not a problem for a homework exercise.

import math

def rounded_log(num: float, number_of_decimals: int, base: int) -> float:
    return round(
             math.log(num, base),
             number_of_decimals
           )


jrbergen
  • 660
  • 5
  • 16
0

Using the decimal module that comes with python you can specify the precision of floating point numbers.

import decimal
decimal.getcontext().prec=5

a = 1.65745678656
b = 2.4584583893

c = decimal.Decimal(a) + decimal.Decimal(b)

print(c)

the output would be 4.1159

For math functions you can try some of the Decimal object's methods. for example:

import math
import decimal
decimal.getcontext().prec = 4

num = 3999              # randomly chosen number
flt = math.log(num)     # uses math.log function

dec = decimal.Decimal(num)   # turns num into a Decimal instance
dec = dec.ln()               # uses the Decimal ln() method

# flt is 8.293799608846818
# dec is 8.294
# flt == dec (rounded to a precision of 4)

print(dec, flt)

the output would be 8.294 8.293799608846818

More info can be found in the python documentation for the module. https://docs.python.org/3/library/decimal.html

Alexander
  • 16,091
  • 5
  • 13
  • 29