Numerically solving an equation

依然范特西╮ 提交于 2019-12-14 03:33:04

问题


Algorithm to be coded in C#:

fn = f(xn)
f′n = df(xn)/dx
∆xn = -fn / f′n
Update: xn+1 = xn + ∆xn
Repeat the process until ∆xn ≤ e

I must use the Newton-Raphson method to solve but I do not know how to do a loop that puts in the next answer each time. How do I compute this?

This is my broken code

double a = 1, Lspan = 30, Lcable = 33, fn, fdn, dfn, j;
fn = (2 * a * (Math.Sinh(Lspan / 2 * a))) - Lcable;
fdn = (2 * (Math.Sinh(Lspan / 2 * a)) - ((Lspan / 2 * a) * Math.Cosh(Lspan / 2    * a)));
dfn = -fn / fdn;
do
    j = a + dfn;
while (dfn > 0.00000000001);

Console.WriteLine( " {0} ",j) ;
Console.ReadKey();

回答1:


Your loop performs the same calculation each time, because neither a or dfn change between iterations. I'm sure I've actually implemented a Newton-Raphson method myself years ago, but I don't remember enough about it to check that your arithmetic is correct without looking it up.

I expect that you intended fdn and dfn to be updated on each iteration - although your pseudocode statement of the method is ambiguous since it implies that only the whole solution is updated on each iteration, whereas actually each term needs to be updated or you'll just keep adding the starting value of ∆xn forever. I think the solution is to move the second, third and fourth lines inside the loop.

Does this make sense?

(It looks as though you were expecting C# to work with symbolic mathematics, which isn't the case. C# is basically procedural within the body of a method, so making an assignment statement fn = some terms; happens once, when the program hits that line. There is no knowledge built into that variable of how it was calculated, it's just a box with a number in it.)



来源:https://stackoverflow.com/questions/20223022/numerically-solving-an-equation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!