0
Why below code gives wrong ans with input of 100 & .0005 while the ans for input of 1000000 & .0005 is absolutly Ok
#include <iostream> using namespace std; int main() { //calculates square root of a positive number. cout<<"please enter a number\n"; float x,y=0,z; cin>>x; cout<<"please enter max tolerence\n"; cin>>z; while(y*y<x) y=y+z; cout <<"The square root of the entered Value is:"<<y; return 0; }
4 Antworten
+ 3
Usually, for numeric approximations, you use some "step" variable, which you use to perform the calculations in every step (in your example, "y=y+z", and another "tolerance" variable (positive, non-zero) to check if your approximation so far is accurate enough. BTW, the standard way to check for accuracy should be sort of "abs(calculation - expected_result) < tolerance" or "abs(calculation_in_this_step - calculation_in_previous_step) < tolerance".
+ 2
Let's say z is your tolerance. I'd define a step variable to iteratively get closer to the result (say it has value .0001). Then I'd write "y=y+step" instead of "y=y+z", and "while(abs(y*y - x)<z)" instead of "while(y*y<z)".
abs(...) gives a measure of the distance between two values –in this case, between y*y (which is your approximation) and x (which is the exact number that you want to get close to). If that distance is smaller than a given tolerance, then you're close enough, and you can say that you got the result.
0
Dear frost
i have also tried in other compiler. btw, with finer tolerrance my result should be better. and in my case results are varying with value of tolerance. its not like finer the tolerance bigger the difference. anyways, can u pls suggest me a solution working in all conditions.
0
Dear Alvaro,
i m not getting what u wanna say. could u pls clarify a lil bit more?