C ++将1加到非常小的数字? [英] C++ Adding 1 to very small number?

查看:70
本文介绍了C ++将1加到非常小的数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想在C ++中计算一个好的Sigmoid函数(高效).所以我必须做类似的事情:
1/(1 + exp(-x))

I'm just trying to compute a good sigmoid function in C++ (and efficient). So i have to do something like:
1/(1 + exp(-x))

问题是,当 X 变大(甚至变小)时, 1 + e 的结果变为0或1

The problem is, when X becomes big (or even small), the result of 1 + e turns to be 0 or 1

例如,
1 + exp(-30)= 1
但这是不正确的...

For example,
1 + exp(-30) = 1
But this is incorrect...

我们如何轻松高效地添加很小(或很大)的数字?

How can we add very small (or big) numbers easily and efficiently ?

数据类型,我正在使用:double

Datatype I am using : double

这是代码段:

double Quaternion::sigmoidReal(double v){
    return 1.0 / ( 1.0 + exp(-v) ) ; 
}

谢谢!

推荐答案

我认为您需要设置 cout 的精度:

I think you need to set the precision of cout:

#include <iostream>
#include <iomanip>

int main()
{
    std::cout << std::fixed;
    std::cout << std::setprecision(30);
    std::cout << (1 + exp(-30)) << std::endl;
    getchar();
    return 0;
}

输出:

1.000000000000093480778673438181

注意:就像人们在评论中指出的那样,部分输出是噪声(当时我没有考虑).我主要是想证明您可以在 setprecision 中输入任意数字.

Note: Like people have noted in the comments, part of the output is noise (which at the time, I didn't consider). I was mostly just trying to demonstrate that you can put an arbitrary number into setprecision.

这与可以保存1倍的最大信息量有关.部分位用于指数,部分位用于实际数字.更准确的方法是打印这样的数字(不设置精度):

This has to do with the maximum amount of information that can be saved in 1 double. Part of the bits is used for the exponent, and part for the actual digits. A more accurate way would be to print the number like this (without setting the precision):

std::cout << 1 << "+" << exp(-30) << std::endl;

输出:

1+9.35762e-14

仍然存在用该实际值保存双精度数的问题.但是,这是有可能的,维基百科提供了一系列与此相关的库:链接.相关文章也有更多解释.

Which still leaves the problem of saving a double with that actual value. However, it is possible, and wikipedia has a list of libraries that help with this: Link. The related article also has some more explanation.

这篇关于C ++将1加到非常小的数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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