简体   繁体   English

如何向上/向下舍入浮点数

[英]How do I round up/down floats

I want to run through two function, f(x) and g(x) for x = 0 to 1000 我想通过两个函数f(x)和g(x)来执行x = 0到1000

My goal is to find which value of x makes f and g intercept. 我的目标是找到x的哪个值使f和g截距。

So, while f(x) != g(x) I want to keep running. 所以, while f(x) != g(x)我想继续运行。

When f(x) = g(x) I want the loop to stop, and return that value of x . f(x) = g(x)我希望循环停止,并返回x值。

My problem:

x is not necessarily an integer. x不一定是整数。 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? 有没有一种聪明的方法可以找出允许出现错误的x的近似浮点值?

Thank you! 谢谢!

If you want to compare the returns from f(x) and g(x) to within some tolerance, you could do: 如果要将f(x)g(x)的回报与某个容差进行比较,可以执行以下操作:

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 使用round函数并将其转换为整数使用

>>> int(round(2.56))
3

Or you could use the Decimal module: 或者你可以使用Decimal模块:

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 在此示例中,您可以将精度分配为5个小数位, getcontext().prec为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. 如果你想找到拦截,比较f(x)g(x)是一种不好的方法,因为相邻步骤之间的变化总是太大而无法在你的公差范围内检测到或者你所做的那么小。我会找到你应该找到的多个拦截。

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 . 相反,你应该寻找f(x)g(x)的相对位置发生变化的点,即从f(x) >= g(x)f(x) < g(x) 反之亦然 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) (注意:这假设f(x)g(x)都是连续函数,因为具有不连续的函数,它们可以在不截断的情况下反转位置)

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. 当然,你想以最好的方式做到这一点,你最好使用众多现有的,经过良好测试的数字根寻找算法之一。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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