迭代总和的C ++代码 [英] C++ Code for an iterative sum

查看:81
本文介绍了迭代总和的C ++代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,

有人可以帮我为迭代方法编写C ++代码吗?
例如:

val = x + sin(val); .......方程1
val的初始计算不同,可以说val = PI-tanz.

我需要在等式1中初次替换此值.然后在后续迭代中替换该答案,直到没有太大差异为止!

我不知道该如何编码!有任何建议吗?

Hello,

Can somebody help me write a c++ code for an iterative method.
For example:

val= x+ sin(val);...................equation 1
where the initial calculation is different for val, lets say val=PI-tanz.

I need to substitute this val intially in equation 1. And then subsitute that answer in the subsequent iteration until There is not much difference!

I wonder how to code that! Any suggestions?

推荐答案

难道不是这样的吗?
Wouldn''t it just be something like:
double prev, val=PI-tan(z);
do {
   prev = val;
   val=x+sin(val);
} while(fabs(prev-val)<epsilon);>


您需要将EPSILON定义为差异不大",例如0.05

祝你好运!


EPSILON is something you need to define as your "not much difference", for example 0.05

Good luck!


还不想去测试它,但是它应该很少(或根本没有)修复程序起作用:
Haven''t bothered to test this, but it should work with little (or no) fixes:
typedef double valuetype; // you didn't tell us the type for val ;-)

class sequencer {
public:
   virtual valuetype getNext(valuetype v) = 0; //prototype for the iteration function
   valuetype getAt(std::size_t iterations, valuetype initial_value) {
      v = initial_value;
      for (std::size_t i = 0; i < iterations; ++i) {
          v = getNext(v);
      }
      return v;
   }
};

class AddSinusSequence : public sequencer {
public:
   virtual valuetype getNext(valuetype v) {
      return v + sin(v);
   }
};

int main() {
   AddSinusSequence ass;
   std::cout << "first value: " << 1.5 << std::endl;
   std::cout << "fifth value: " << ass.getAt(5, 1.5) << std::endl;
   return 0;
}


请注意,如果您实际上只对一个函数感兴趣,那么实际上就不需要这两个类:我仅使用这些类作为将要迭代的函数与基于该函数进行实际计算分离的一种方法.

[edit]添加了丢失的: public sequencer [/edit]

[edit2]简单版本:


Note that there is in fact no need for the two classes if there is really only one function you''re interested in: I only used the classes as a means to separate the function you want to iterate from the actual calculation based on that.

[edit] added missing : public sequencer [/edit]

[edit2] the simple version:

double AddSinus(double value) {
   return value + sin(value);
}
double getAt(unsigned i, double initial_value) {
   double v = initial_value;
   for (unsigned i=0; i < iterations; ++i)
      v = AddSinus(v);
   return v;
}
int main() {
   double initial = 1.5;
   double v_at_5 = getAt(5, initial);
   // output as needed ...
   return 0;
}


[/edit2]


[/edit2]


这篇关于迭代总和的C ++代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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