如何确保函数在C/C ++中返回一致的浮点值? [英] How to ensure the function return consistent floating point values in C/C++?

查看:50
本文介绍了如何确保函数在C/C ++中返回一致的浮点值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何确保函数在C/C ++中返回一致的浮点值?

How to enure the function return consistent floating point values in C/C++?

我的意思是:如果ab是浮点型的,如果我写了一个多项式函数(使用浮点型参数并返回浮点型结果),则将其称为polyfun(),编译器可以确保:

I mean: if a and b are of floating point type, if I wrote a polynomial function (which takes floating point argument and returns floating point results), lets call it polyfun(), do the compiler can ensure that:

如果a==b,则为polyfun(a)==polyfun(b),这意味着数学运算/四舍五入的顺序在运行时是否一致?

if a==b, then polyfun(a)==polyfun(b), which means the order of maths ops/rounding up are consistent at runtime?

推荐答案

语言标准不保证可重复的结果.通常,允许C实现以比标称类型更高的精度评估浮点表达式.它可能以不可预测的方式进行操作,例如在一个地方而不是在另一个地方内联一个函数调用,或者在两个地方将一个内联函数调用内联,但是在一个地方,将结果缩小为标称类型以将其保存在堆栈上,然后再进行检索并将其与另一个值进行比较.

Reproducible results are not guaranteed by the language standards. Generally, a C implementation is permitted to evaluate a floating-point expression with greater precision than the nominal type. It may do so in unpredictable ways, such as inlining a function call in one place and not another or inlining a function call in two places but, in one place, narrowing the result to the nominal type to save it on the stack before later retrieving it to compare it to another value.

此问题中有一些其他信息,并且可能还有其他也是重复的.

Some additional information is in this question, and there are likely other duplicates as well.

处理此问题的方法因语言和实现(尤其是编译器)而异,因此,如果指定使用的是C或C ++实现,则可能会获得更多信息,包括目标系统的详细信息以及是否进行搜索有关问题.

Methods of dealing with this vary by language and by implementation (particularly the compiler), so you might get additional information if you specify what C or C++ implementation you are using, including the details of the target system, and if you search for related questions.

这篇关于如何确保函数在C/C ++中返回一致的浮点值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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