简体   繁体   中英

How do I round up/down floats

I want to run through two function, f(x) and g(x) for x = 0 to 1000

My goal is to find which value of x makes f and g intercept.

So, while f(x) != g(x) I want to keep running.

When f(x) = g(x) I want the loop to stop, and return that value of x .

My problem:

x is not necessarily an integer. Actually, in my case, I have to deal with many decimals.

Is there a smart way to figure out an approximate float value of x that allows some error?

Thank you!

If you want to compare the returns from f(x) and g(x) to within some tolerance, you could do:

if abs(f(x) - g(x)) < tolerance:

rather than

if f(x) == g(x):

Use the round function and to convert it to a integer use

>>> int(round(2.56))
3

Or you could use the Decimal module:

from decimal import *

getcontext().prec = 5

x = Decimal(22)/ Decimal(7)
print x
#3.1429

In this example you can have a precision of 5 decimal places as you've assigned , getcontext().prec to 5

If you want to find interceptions comparing f(x) to g(x) is a poor way to do it, because there's always the possibility that the change between adjacent steps will be too large to detect within your tolerance or so small that you'll find multiple interceptions where you should find one.

Instead you should look for points where the relative position of f(x) and g(x) changes, ie the step where it goes from f(x) >= g(x) to f(x) < g(x) or vice versa . Tracking the previous state should allow you to find all interception points.

(NB: this assumes both f(x) and g(x) are continuous function since with discontinuous functions its possible for them to reverse positions without intercepting)

And, of course, it you want to do it in the best possible way, you're better off using one of the many existing and well-tested numerical root-finding algorithms available.

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