首页 \ 问答 \ #inf c ++ visual studio(#inf c++ visual studio)

#inf c ++ visual studio(#inf c++ visual studio)

我在计算双重总和时遇到了问题。 当我将迭代设置为100000时,函数Asian_call_MC仍然返回一个数字。 但是,当我将迭代设置为大约500000及以上时,它开始返回1.#INF。 有人能告诉我它为什么会发生以及如何解决它? 我正在使用visual studio 2013来编写c ++代码。

double Avg_Price(double init_p, double impl_vol, double drift, int step, double deltasqrt)
{
//Calculate the average price of one sample path
//delta  = T/ step
//drift = (risk_free - div_y - impl_vol*impl_vol / 2)*(T / step)
double Sa = 0.0;
double St = init_p;

for (int i = 0; i < step; i++)
{
    St = St*exp(drift + impl_vol*deltasqrt*normal_gen());
    //Sa = Sa * i / (i + 1) + St / (i + 1);
    Sa += St;
}
Sa = Sa / double(step);
return Sa;
}


double Asian_call_MC(double strike_p, double T, double init_p, double impl_vol, double risk_free, double div_y, int iter, int step)
{
//Calculate constants in advance to reduce computation time
double drift = (risk_free - div_y - impl_vol*impl_vol / 2)*double(T / step);
double deltasqrt = sqrt(double(T / step));


//Generate x1, average x and y
double cur_p = Avg_Price(init_p,impl_vol,drift,step,deltasqrt);
double pay_o=0.0;
double x = max(cur_p - strike_p,0.0);
//double y = pow(x, 2.0);


//Generate x2 to xn
for (int i = 0; i < iter; i++)
{
    cur_p = Avg_Price(init_p, impl_vol, drift, step, deltasqrt);
    x = max(cur_p - strike_p,0.0);
    //double q = double(i) / double(i + 1);
    //pay_o = pay_o *i/(i+1) + x / (i + 1);
    pay_o += x;
    //y = (1 - (1 / (i + 1)))*y + x*x / (i + 1);
}
//pay_o = pay_o / double(iter);
//stdev = sqrt((y - pow(pay_o , 2)) / (iter - 1));
//return pay_o*exp(-risk_free*T) ;
return pay_o;
}

I came across question in calculating the sum of a double. When I set iteration to 100000, the function Asian_call_MC still return a number. However, when I set iteration to around 500000 and above, it begin to return 1.#INF. Can someone tell me why it happens and how to solve it? I am using visual studio 2013 to write c++ code.

double Avg_Price(double init_p, double impl_vol, double drift, int step, double deltasqrt)
{
//Calculate the average price of one sample path
//delta  = T/ step
//drift = (risk_free - div_y - impl_vol*impl_vol / 2)*(T / step)
double Sa = 0.0;
double St = init_p;

for (int i = 0; i < step; i++)
{
    St = St*exp(drift + impl_vol*deltasqrt*normal_gen());
    //Sa = Sa * i / (i + 1) + St / (i + 1);
    Sa += St;
}
Sa = Sa / double(step);
return Sa;
}


double Asian_call_MC(double strike_p, double T, double init_p, double impl_vol, double risk_free, double div_y, int iter, int step)
{
//Calculate constants in advance to reduce computation time
double drift = (risk_free - div_y - impl_vol*impl_vol / 2)*double(T / step);
double deltasqrt = sqrt(double(T / step));


//Generate x1, average x and y
double cur_p = Avg_Price(init_p,impl_vol,drift,step,deltasqrt);
double pay_o=0.0;
double x = max(cur_p - strike_p,0.0);
//double y = pow(x, 2.0);


//Generate x2 to xn
for (int i = 0; i < iter; i++)
{
    cur_p = Avg_Price(init_p, impl_vol, drift, step, deltasqrt);
    x = max(cur_p - strike_p,0.0);
    //double q = double(i) / double(i + 1);
    //pay_o = pay_o *i/(i+1) + x / (i + 1);
    pay_o += x;
    //y = (1 - (1 / (i + 1)))*y + x*x / (i + 1);
}
//pay_o = pay_o / double(iter);
//stdev = sqrt((y - pow(pay_o , 2)) / (iter - 1));
//return pay_o*exp(-risk_free*T) ;
return pay_o;
}

原文:https://stackoverflow.com/questions/36782966
更新时间:2019-12-07 10:14

最满意答案

看起来你想要计算平均值。 大多数人学习计算均值的方法是将所有值相加,然后将总和除以贡献总和的值的数量。

这种方法有一些与之相关的问题 - 例如,在一起添加许多值可能会给持有它的变量一个太大的总和。

经常使用另一种技术,其累积“运行”均值而不是总和。 运行平均值始终是已累积的所有样本的平均值,因此它永远不会爆炸成溢出(浮点无穷大)值(除非其中一个累积样本为无穷大)。

下面的示例演示了如何计算运行平均值。 它还计算总和并显示总和/计数与运行平均值的比较(表明它们是相同的 - 我没有让它运行足够长以溢出总和)。

该示例使用C-Library rand(),用于演示目的 - 我只需要一些东西来计算平均值。

#include <cstdlib>
#include <ctime>
#include <iostream>
#include <iomanip>

int main() {
        srand(static_cast<unsigned>(time(0)));

        double count = 0;
        double running_mean = 0;
        double sum = 0;

        auto start = time(0);
        auto end = start + 5;
        while(time(0) < end) {
            double sample = rand();
            count += 1;
            running_mean += (sample - running_mean)/count;
            sum += sample;
        }

        std::cout << std::setprecision(12);
        std::cout << "running mean:" << running_mean << "  count:" << count << '\n';
        double sum_mean = sum / count;
        std::cout << "sum:" << sum << "  sum/count:" << sum_mean << '\n';
}

编辑:他已经尝试过这个 - 这个技术出现在我在OP代码中遗漏的注释掉的行中

与通过累积总和来计算平均值不同,运行平均技术不能简单地在某个时刻溢出。 所以知道他已经尝试了这个并且它没有帮助解决这个问题,可能的原因就是迭代的一个术语本身就是INF。 一旦添加单个INF术语,累积的总和或平均值将变为INF并保持INF。

最可能的代码部分是在参数内部使用的normal_gen()用于调用exp函数。 名称normal_gen()听起来像是正常分布的随机值的来源。 通常的实现采用Box-Muller变换,其不能产生超过平均值大约7个标准偏差的值。 因此,如果Box-Muller生成器导致INF,它可能会在比报告的迭代次数更少的情况下发生。 然而,更高级的生成器可以产生更多的极值 - 理想情况下,正态分布具有产生任何有限实际值的非零概率。

如果一个随机大的Normal样本是造成问题的原因,那么它与迭代计数增加的相关性就不会是更多的迭代使总和膨胀,通过添加更多的值来溢出 - 这将是更多的迭代给了程序一个更好的机会击中一个不太可能的随机值,这将导致一个INF术语。


It looks like you want to compute mean values. The the way most people learn to calculate a mean is to sum up all the values, then divide the sum by the number of values which contributed to the sum.

This method has a few problems associated with it -- for example, adding many values together might give a sum which is too large for the variable holding it.

Another technique is often used, which accumulates a "running" mean instead of a sum. The running mean's value is always the mean value for all samples already accumulated, so it never blows up into an overflow (floating-point infinity) value (except when one of the accumulated samples was infinity).

The example below demonstrates how to calculate a running mean. It also calculates the sum and shows how sum/count compares to the running mean (to show that they are the same -- I haven't let it run long enough to overflow the sum).

The example uses the C-Library rand(), for demonstration purposes -- I just needed something to calculate mean values from.

#include <cstdlib>
#include <ctime>
#include <iostream>
#include <iomanip>

int main() {
        srand(static_cast<unsigned>(time(0)));

        double count = 0;
        double running_mean = 0;
        double sum = 0;

        auto start = time(0);
        auto end = start + 5;
        while(time(0) < end) {
            double sample = rand();
            count += 1;
            running_mean += (sample - running_mean)/count;
            sum += sample;
        }

        std::cout << std::setprecision(12);
        std::cout << "running mean:" << running_mean << "  count:" << count << '\n';
        double sum_mean = sum / count;
        std::cout << "sum:" << sum << "  sum/count:" << sum_mean << '\n';
}

Edit: He already tried this -- the technique appeared in commented-out lines that I missed in the OP's code

Unlike computing the average value by accumulating a grand sum, the running mean technique cannot simply overflow at some point. So knowing that he already tried this and that it didn't help the problem, the probable cause becomes that one of the iteration's terms is, itself INF. As soon as a single INF term is added, the accumulated sum or mean will become INF and stay INF.

The most likely section of code was normal_gen() used inside the argument for a call to the exp function. The name normal_gen() sounds like a source of Normally-distributed random values. The usual implementation employs a Box–Muller transform, which cannot produce values over about 7 standard-deviations away from the mean. So if a Box-Muller generator was causing the INF, it would probably occur within fewer iterations than reported. However, more advanced generators can produce more extreme values -- ideally a Normal distribution has a nonzero probability of producing any finite real value.

If a randomly large Normal sample is what was causing the problem, its correlation with increased iteration count would not be that more iterations inflate the sum, to the point of overflowing by adding more values -- it would be that more iterations gave the program a better chance to hit an unlikely random value which would result in an INF term.

2016-04-23

相关问答

更多

VisualBasic是否支持WSDL2.0?(Does VisualBasic support WSDL2.0?)

而VB.NET支持它。 我不认为VB6客户端在使用现已退役的SOAP Toolkit 3.0时会执行这些操作,这些客户端或者需要对.NET运行时中运行的组件执行一些COM Interop操作,或者将其Excel表格升级到Office 2007。 While VB.NET supports it. I don't think that VB6 clients do when using the now retired SOAP Toolkit 3.0, those clients will eit

使用Ruby的win32ole库在.doc中插入图像(insert image in .doc using win32ole library of Ruby)

你可以通过调用Document.InlineShapes.AddPicture()方法来做到这一点。 以下示例在第二句之前将图像插入到活动文档中。 require 'win32ole' word = WIN32OLE.connect('Word.Application') doc = word.ActiveDocument image = 'C:\MyImage.jpg' range = doc.Sentences(2) params = { 'FileName' => image, 'L

如何在C#后面的代码中显示PictureBox(How to display a PictureBox from behind code in C#)

由于您使用的PictureBox是Winforms控件,因此您需要将WindowsFormsHost控件添加到Wpf窗体并将PictureBox添加到其中。 无论何时动态创建控件,都需要将其添加到Form或Container对象中,否则将无法显示。 即这样的事情。 MainWindow.xaml <Window x:Class="WpfApplication1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/x

包含一个表单的多个页面?(Multiple Pages withing one Form? C#)

我将使用UserControl实现此功能。 单击按钮时会显示一个UserControl 。 我创建了一个接口(例如IView ),它将由声明常用功能的每个UserControl实现,例如检查是否可以从一个切换到另一个(如表单的OnClosing事件)的方法,如下所示: public interface IView { bool CanClose(); } public UserControl View1: IView { public bool CanClose() {

如何将粘贴从记事本复制到vim?(How to copy paste from notepad to vim?)

在Vim中复制您喜欢的任何内容,按Shift+Insert将剪贴板中的内容粘贴到文件中。 确保您处于Insert Mode 。 只要我尝试过,它在Ubuntu 12.10中运行良好。 编辑在粘贴之前,建议您进入vim的paste mode (通过:set paste ),以防您遇到不正确的自动缩进等不需要的功能。 (感谢@DmitryFrank) Copy whatever you like, in Vim, press Shift+Insert to paste content in clip

在C#中检查空值对象的最佳语法是什么(What is the best syntax for checking for null value objects in C#)

在C#中,你不能这样做 if (MyObject) 检查null s。 这是一个编译时错误(如果该类没有隐式布尔转换运算符)。 if (!MyObject) 如果类不重载operator !也是无效的operator ! 返回一个布尔值(或可隐式转换为布尔值的值)。 所以你必须坚持obj == null和obj != null 。 总而言之,非主观原因是能够编译你的代码! 更新(故事): 曾几何时,在古代的C中,没有bool型。 零被认为是false并且每个非零值都被认为是true 。 你

网址:目录或带有扩展名的网页[已关闭](URL: Directory like or Pages with extension [closed])

这比建立网站更普遍。 对于您必须组织的大量文件,这是一个很好的做法。 https://stackoverflow.com/是Web服务器的根,只要Web服务器知道它就是文件系统的根目录(而不是过度复杂化虚拟主机等)。 stackoverflow.com/questions/将进入名为问题的目录。 通常这些目录将包含index.html或index.php以及主页面正常运行所需的一系列其他文件|脚本|页面。 我认为这不会影响您的排名。 如果您经常在网址栏中输入您想要的内容,而不是点击主站点上的链接

从十进制转换为十进制?(Convert ToDecimal from Decimal? returns sometimes returns null instead of 0)

LINQ查询从来没有实际执行为C#代码。 它被编译成一个表达式,该表达式被传递给一个查询提供者,该查询提供者能够检查你写的内容并且尽其所能地创建语义上等价的SQL查询 。 当然,尽管它尽最大可能具有完全相同的语义,但它不会总是成功,因为查询提供程序没有正确地转换这些语义,或者有时是因为查询所写的数据库没有用期望的语义进行操作(或者可能是因为它故意创建稍微不同的语义)。 The LINQ query is never actually executed as C# code. It is comp

相关文章

更多

最新问答

更多
  • asp.net任意用户信息(asp.net arbitrary user info)
  • 如何使用python计算docx文件中表中行的值(How to count the row's values in tables in docx file by using python)
  • MySQL:用户访问和数据库覆盖(MySQL: User access and DB overwriting)
  • 还有另一种“使用未分配的局部变量”的问题(Yet Another “Use of unassigned local variable 'whatever' ” question)
  • 开源证书颁发机构软件(Open source certificate authority software)
  • Rails中的迭代form_for是在create上添加模型的所有实例(Iteration in Rails form_for is adding all instances of model on create)
  • 如何扩展我的表视图单元格?(How to expand my table view cell?)
  • 如何使用SPARQL区分Thing和无生命对象(How to differentiate between a Thing and an inanimate object with SPARQL)
  • 在IdentityServer中,Client Secrets和Scope Secrets有什么区别?(In IdentityServer, what is the difference between Client Secrets and Scope Secrets?)
  • 如何在具有附加类时重写类(How do I override a class when it has a attached class)
  • 如何使用Git在Azure上部署C#,MVC4应用程序(How to deploy a C#, MVC4 application on Azure using Git)
  • Sitecore 7内容搜索爬网程序根目录之外的索引项(Sitecore 7 Content Search indexing items outside of crawler root)
  • 我应该在线课程使用utf-8编码吗?(Should I use utf-8 encoding for an online course?)
  • 如何在Cucumber-JS步骤定义中使用Node-mysql连接到MySQL?(How to connect to MySQL using Node-mysql in a Cucumber-JS step definition?)
  • 在MVC 4中的google.maps.LatLng(lat,lon)中将JSON字符串值分配给纬度和经度(Assign the JSON string value to Latitude and Longitude in google.maps.LatLng(lat,lon) in MVC 4)
  • awk:通过特定的分隔符删除字符串(awk: remove strings by specific delimiter)
  • 如何测试Vista的应用程序(How to test app for Vista)
  • Elasticsearch聚合器 - 缺失值的工作原理(Elasticsearch aggregators - How missing values work)
  • 绘制datetime.date熊猫(Plot datetime.date pandas)
  • PostgreSQL作为WSO2 EI和APIM + IS的数据源(PostgreSQL as datasource for WSO2 EI and APIM+IS)
  • 如何使用bash在postgres中运行alter table脚本(How to run alter table script in postgres using bash)
  • 可能使用PHP阻止整个美国州访问我的网站?(Might it be possible to block an entire US state from accessing my site, using PHP?)
  • restangular删除并输入错误网:: ERR_NAME_NOT_RESOLVED(restangular remove and put error net::ERR_NAME_NOT_RESOLVED)
  • 常见问题解答的Modx(Revolution)搜索功能(Modx(Revolution) search function for FAQs)
  • Rubymine如何使用远程口译员和Git?(How Does Rubymine Work With Remote Interpreters and Git?)
  • prepareForSegue和PerformSegueWithIdentifier发件人(prepareForSegue and PerformSegueWithIdentifier sender)
  • postgrsql与PowerShell无提示安装问题(postgresql silent installation issue with powershell)
  • 比较两个greps的输出(Comparing output from two greps)
  • 使用.NET RIA Data Services删除Silverlight 3中的数据(Deleting data in Silverlight 3 with .NET RIA Data Services)
  • 此行中AND运算符的含义(meaning of the AND operator in this line)