Welcome to the world of coding! When you're running a loop, the code inside of it will be executed several times. While it's intuitive to think that by defining y
as a function of x
means y
updates when x
does, this unfortunately isn't the case. In order to update the value, you have to re-evaluate it each time you run through the loop.
public static void main(String[] args) {
double x = 0.1;
double x2 = Math.pow(x,2);
double y = 4*x2 + 5*x - 3;
double counter = 0.1;
while(counter <= 1.0)
{
System.out.print(y);
counter += 0.1;
//re-evaluate x, x2, and y here
x += 0.1;
x2 = Math.pow(x,2);
y = 4*x2 + 5*x - 3;
}
}
This works, but we can do better. If you'd like to try updating y dynamically with respect to x, consider writing a function:
double calculateY(double x) {
double value = 4*(x*x) + 5*x - 3;
return value;
}
In your loop, you would call the function like this:
y = calculateY(x);
Functions are a very good way to quickly and easily perform complex sets of code. As a bonus, if you want to calculate y
somewhere else in your code, you don't have to copy-paste from your loop. This is good practice, because if you later need to change the equation, you only need to change it once, in the function, instead of in several places, where you might make mistakes.
Here's what the modified code might look like. Note that I start the variables at 0 - this can help reduce confusion.
double calculateY(double x) {
double value = 4*(x*x) + 5*x - 3;
return value;
}
public static void main(String[] args) {
double x = 0;
double y = 0;
while (x <= 1.0) {
x += 0.1;
y = calculateY(x);
System.out.print(y);
}
}
Much less clutter! This code is easy to read, and easier to edit. If you want to calculate y
a different way, you need only modify the calculateY
function - with the added benefit that you don't need to recalculate, or even include, the x2
or counter
variables.