Skip to content
Advertisement

Trying to create a calculator for Newton’s Square Root without using built-in things for school. I have it down but the math is a little off

I will be able to accept an answer in 6 minutes. For now going to state that my answer has successfully been solved by Elliott Frisch. He provided a solution to fix the problem I ran into.

When attempting to do the “Equation” it correctly performs the action but seems to be off. Off being that it doesn’t really display it in a way I want it to. An example is this:

Equation = √ N ≈ ½(N/A + A)

// 1/2(121/10+10) which is 11.05.

// My program on the other hand does this:

var FirstTextFieldData = Integer.parseInt(TextFieldOne.getText()); // Positive Number
var SecondTextFieldData = Integer.parseInt(TextFieldTwo.getText()); // Educated Guess

double Equation = (double)1 / 2 * ((FirstTextFieldData / SecondTextFieldData) + SecondTextFieldData);

// FirstTextFieldData being the input for the positive number (N).
// SecondTextFieldData being the educated guess (A).

// Let's say I did:

double Equation = (double)1 / 2 * ((121 / 10) + 10);

// It does it correctly but displays as 11.0. I need it to display as 11.05.

Everything seems to be right. Nothing seems to have gone wrong and the equation is performing it’s action correctly. The only “major” problem I have is that it’s not displaying in a way I want it to. I tried changing some things like removing “(double)” but it just makes the equation 0.0 and incorrect.

Any help? I’m confused at this point and been stuck for a few good minutes. Very sorry if my formatting and explanation is not very good. Tried to explain this as best as I could.

I want to state also that yes I could be using Math library from Java but my instructor specifically stated to NOT use any “library” that may make it easier to do this.

Resources I have used: https://www.school-for-champions.com/algebra/square_root_approx.htm

Edit: Added a period at the end of the title.

Advertisement

Answer

You are using integer math in multiple places. Solution 1:

double Equation = (1 / (double) 2) * ((121 / (double) 10) + 10);

Solution 2:

double Equation = 0.5 * ((121 / 10.0) + 10);

Both will set Equation to 11.05. Alternatively, you can use variables as your terms – which may well be easier to read. Like,

double N = 121;
double A = 10;
double Equation = 0.5 * ((N / A) + A);
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement