给定数字位于哪个段中? [英] In which segment a given number lies in?

查看:116
本文介绍了给定数字位于哪个段中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设有 n (整数)连续段长度 l (浮点)。也就是:

Suppose to have n (integer) contiguous segments of length l (floating point). That is:

Segment 0 = [0, l)
Segment 1 = [l, 2*l)
Segment 2 = [2*l, 3*l)
... 
Segment (n-1) = [(n-1)*l, n*l) 

给定一个数字 x

我的第一个想法是以下内容:

My first idea is the following:

int segmentId = (int) floor(x/l);

无论如何,这有时不起作用。例如,考虑

Anyway, this sometimes does not work. For example, consider

double l = 1.1;
double x = 5.5;
int segmentId = (int) floor(x/l); //returns 5


double l = 1.1;
double x = 6.6;
int segmentId = (int) floor(x/l); //returns 5!!!

当然,由于有限算术,这不能很好地工作。
可能需要一些额外的检查才能有一个强大的实现,但我真的不知道如何继续进行。

Of course, due to finite arithmetic, this does not work well. Maybe some extra checks are required in order to have a robust implementation, but I really don't know how to proceed further.

推荐答案

您的问题是什么?

double l = 1.1;
double x = 6.6;

您将获得存储在 l x 1.1 6.6 略有不同。之后, int segmentId =(int)floor(x / l); 为那些略有不同的数字而不是原始数字确定正确的段。

you get 2 numbers stored in l and in x, which are slightly different than 1.1 and 6.6. After that, int segmentId = (int) floor(x/l); determines the correct segment for those slightly different numbers, but not for the original numbers.

您可以使用十进制浮点数据类型而不是二进制来解决这个问题。您可以检查 C ++十进制数据类型 C ++的完全十进制数据类型,或者自己实现十进制数据类型。

You can solve this problem by using a decimal floating point data type instead of binary. You can check C++ decimal data types and Exact decimal datatype for C++? for the libraries, or implement the decimal data type yourself.

但是问题仍然是数字,这在有限十进制浮点中是不可表示的,例如 1/3 (循环分数), sqrt(2)(不合理), pi (超越)等。

But still the problem will remain for numbers, which are not representable in finite decimal floating point, such as 1/3 (circulating fraction), sqrt(2) (irrational), pi (transcendental), etc.

这篇关于给定数字位于哪个段中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆