给定数字位于哪个段中?

编程入门 行业动态 更新时间:2024-10-25 04:15:27
本文介绍了给定数字位于哪个段中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

假设有 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.

更多推荐

给定数字位于哪个段中?

本文发布于:2023-11-30 21:31:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1651532.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数字

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!