473,748 Members | 2,320 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to Solve a Root...

always wondered how a computer might go about doing this...
i'm taking calculus at university... and we went over newton's method.
i found this interesting...

------------------------------
#include <cstdlib>
#include <iostream>
#include <cmath>

using namespace std;

double f1(double x);
double f2(double x, double y);

int main(int argc, char *argv[])
{
double x = 5;
cout << f1(x) << endl;
cout << sqrt(x) << endl;

system("PAUSE") ;
return EXIT_SUCCESS;
}

double f1(double x)
{
return f2(x,x/2);
}

double f2(double x, double y)
{
double z = y - (y*y-x)/(2*x);
if( y == z ) return z;
else return f2(x,z);
}
---------------------------

will work for cube roots and others if you just tweak the formula.

Dec 2 '05 #1
13 1497
(just thought i'd share. no question involved)

Dec 2 '05 #2

Mark wrote:
always wondered how a computer might go about doing this...
i'm taking calculus at university... and we went over newton's method.
i found this interesting...

------------------------------
#include <cstdlib>
#include <iostream>
#include <cmath>

using namespace std;

double f1(double x);
double f2(double x, double y);

int main(int argc, char *argv[])
{
double x = 5;
cout << f1(x) << endl;
cout << sqrt(x) << endl;

system("PAUSE") ;
return EXIT_SUCCESS;
}

double f1(double x)
{
return f2(x,x/2);
}

double f2(double x, double y)
{
double z = y - (y*y-x)/(2*x);
if( y == z ) return z;
I thought it was bad to directly compare floats?
else return f2(x,z);
}
---------------------------

will work for cube roots and others if you just tweak the formula.


I love recursion as much as the next guy, but in this mathematical case
I see huge potential for a stack overflow. Maybe this should be rolled
into a loop instead. Might actually look cleaner.

Cheers,
Andre

Dec 2 '05 #3

Mark wrote:
always wondered how a computer might go about doing this...
i'm taking calculus at university... and we went over newton's method. will work for cube roots and others if you just tweak the formula.


You might want to look into the Runge-Kutta method. Quite robust. I
coded it up once many years ago...

Dec 2 '05 #4
in*****@gmail.c om wrote:
I thought it was bad to directly compare floats?
i have no idea... never heard that before.
I love recursion as much as the next guy, but in this mathematical case
I see huge potential for a stack overflow. Maybe this should be rolled
into a loop instead. Might actually look cleaner.
well. when i've worked these out on paper... they only took about 6 or
8 "loops" to get it accurate to about 8 decimal places.... it really
shouldn't stack that much at all. *i think*

but yes, maybe a for loop would be more efficient...but ... oh well.
go**********@gm ail.com wrote: You might want to look into the Runge-Kutta method. Quite robust. I
coded it up once many years ago...


Runge-kutta eh? perhaps i shall look into it. you wouldnt happen to
know what method cmath uses, would you?

i suppose i could open the library and check myself.... if i can
understand it.

Dec 2 '05 #5
Mark wrote:
in*****@gmail.c om wrote:

I thought it was bad to directly compare floats?

i have no idea... never heard that before.


"Bad" may be too strong, but it should be done with care. A computer
will compare 2.0 and 1.999999 as unequal; sometimes this is undesirable.
Often rather than comparing for equality it makes more sense to see if
the absolute value of the difference is less than some small number (say
0.0001).

go**********@gm ail.com wrote:
You might want to look into the Runge-Kutta method. Quite robust. I
coded it up once many years ago...


Runge-Kutta is a numerical method for solving differential equations.
Quite different from root finding.

-Mark
Dec 2 '05 #6
Mark wrote:
well. when i've worked these out on paper... they only took about 6 or
8 "loops" to get it accurate to about 8 decimal places.... it really
shouldn't stack that much at all. *i think*


Seems not fast enough. Some years ago, talking about fixed point
calculations for writing graphics demos, I recommended to try the Hero
method (a Newton's variant specific for square roots), and the result was
that just 4 iterations were enough for 3-d calculus.

Buy will be better to talk about this things in group about graphics
programming.

--
Salu2
Dec 2 '05 #7

Mark P wrote:
Runge-Kutta is a numerical method for solving differential equations.
Quite different from root finding.


Not really. Often these forms can be converted into each other,
certainly
for the trivial forms used here. And sqr(x)=y implies y*y-x = 0, which
is
truly trivial. Runga-Kutta takes three points, IIRC, which means it's a
single iteration for second-degree functions like that. Newton uses two
points, which means it's only a single iteration for first-degree
functions
(lines).

HTH,
Michiel.

Dec 2 '05 #8

Mark wrote:
in*****@gmail.c om wrote:
I love recursion as much as the next guy, but in this mathematical case
I see huge potential for a stack overflow. Maybe this should be rolled
into a loop instead. Might actually look cleaner.
well. when i've worked these out on paper... they only took about 6 or
8 "loops" to get it accurate to about 8 decimal places.... it really
shouldn't stack that much at all. *i think*


I've measured it with a non-trivial number like '12345.6789' and it
took 3669 iterations. That's quite a bit of stack pressure.

but yes, maybe a for loop would be more efficient...but ... oh well.


Here's my entry :D (based on your formula):

double my_sqrt( const double & x )
{
double y = 0;
double z = 1;

while ( y != z )
{
z = y;
y = y - (y * y - x) / (2 * x);
}

return y;
}

Cheers,
Andre

Dec 2 '05 #9
Mark P wrote:
Mark wrote:
in*****@gmail.c om wrote:

I thought it was bad to directly compare floats?

i have no idea... never heard that before.


"Bad" may be too strong, but it should be done with care. A computer
will compare 2.0 and 1.999999 as unequal; sometimes this is undesirable.
Often rather than comparing for equality it makes more sense to see if
the absolute value of the difference is less than some small number (say
0.0001).


See the FAQ:

http://www.parashift.com/c++-faq-lit...html#faq-29.17

Cheers! --M

Dec 2 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
2242
by: lawrence | last post by:
My company is leasing a server from Interland, which is a very large web hosting company. I assume Interland knows how to set up a BSD server with the usual add-ons, including PHP. But when I run phpinfo(), I get information that makes it seem like PHP is running as root. Isn't this a security problem? This is some of the info I'm getting back from phpinfo():
17
3541
by: Just | last post by:
While googling for a non-linear equation solver, I found Math::Polynomial::Solve in CPAN. It seems a great little module, except it's not Python... I'm especially looking for its poly_root() functionality (which solves arbitrary polynomials). Does anyone know of a Python module/package that implements that? Just
15
4161
by: Stig Brautaset | last post by:
Hi group, I'm playing with a little generic linked list/stack library, and have a little problem with the interface of the pop() function. If I used a struct like this it would be simple: struct node { struct node *next; void *data; };
13
12748
by: Kishor | last post by:
Hi Friends Please help me to write a C program to find the 5th (fifth) root of a given number. Ex:(1) Input : 32 Output : 5th root of 32 is 2 Ex:(1) Input : 243 Output : 5th root of 243 is 3 Click here : www.c4swimmers.esmartguy.com to Test Your C Programming Strengths.
3
1704
by: Nalaka | last post by:
Hi, I have an asp.net web application (www.myWebSite), and a subweb application (www.myWebSite/subSite). How do I set it so that, subweb application (www.myWebSite/subSite) be the root application..... so that, when a user types www.myWebSite/subSite, it actualy, shows pages off subweb.
8
4807
by: vj | last post by:
Hi all, I want to solve the two equations u*tan(u)=w and u^2 + w^2=V^2, where V is a known constant, and u and w are the two unknowns to be determined. Please can someone suggest me how to write a code and solve these equations in C or C++? I am not an expert, but have elementary working knowledge of C.
1
1428
by: mostafij | last post by:
// This code write random data into a file and every 5 seconds this //program send 5 seconds data into another file. #include <HEADER FILES> FILE *f1,*f2; int main(int argc, char *argv) { int i,j,m=0,n=0; char buf;
14
3788
by: Mohamed Mansour | last post by:
Hey there, this will be somewhat a long post, but any response is appreciated! I have done many PInvoke in the past from C++ to C#, but I did PInvoke within C# not C++/CLI. Can someone explain more why C++/CLI would be better to PInvoke than doing the PInvoke in C#? Because, usually in C# as you already know we use DLLImport and extern
2
2813
by: shiva359 | last post by:
Hi , could someone throw some light on why do default software when installed ( as root for creating an instance leaves us with some world accessable directories & some world executable files & some world readable files . I am facing this issue on how to explain to Unix Audit Team how db2 is ensuring security even after allowing such permissions at software level . if I give 750...
0
8983
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
1
9310
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9236
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8235
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6072
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4592
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3298
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2774
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2206
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.