简体   繁体   中英

Smallest Number in Python

PROBLEM STATEMENT: Write a Python script to determine the smallest positive double number in Python.

Your code should produce a variable called smallest_num which is the smallest double number in Python.

Your script should determine this value in a systematic manner. You may NOT simply call a built-in function that returns this value or access a built-in variable that contains this information. This includes np.finfo() and other built-in functions or variables.

The setup code gives the following variables:

Your code snippet should define the following variables:

Name Type Description

smallest_num floating point The smallest number possible in Python

Attempted Solution

import numpy as np
import math

def machineEpsilon(func=float):
    machine_epsilon = func(1)
    while func(1)+func(machine_epsilon) != func(1):
        machine_epsilon_last = machine_epsilon
        machine_epsilon = func(machine_epsilon) / func(2)
    return machine_epsilon_last

sum_f = machineEpsilon(np.float64)

smallest_sum = float(sum_f)
print(isinstance(smallest_sum, float))
print(smallest_sum)

Output True 2.220446049250313e-16

However, I am unable to get the correct answer. As the true smallest number is much smaller than the printed value. I know this number will be underflow to zero and I might want to do some comparison here. But i am a bit stuck. Any thoughts?

Probably the most reasonable thing to do would be to directly compute the next double-precision float after 0.0:

smallest_num = np.nextafter(0, 1)

This does not simply call a built-in function that returns the smallest positive double-precision float, or access a variable pre-set to that value. However, people get weird when they see function call syntax in problems like this, so it risks being marked incorrect anyway.

Taking advantage of how IEEE754 floating-point representation and rounding works, we can start with 1.0 and divide by 2 until the next division would underflow:

smallest_num = 1.0
while smallest_num / 2:
    smallest_num /= 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM