How Come My Value Keeps Outputting 1.0? - General Polynomial Evaluator - java

I'm currently working on a program for my lab class and I am needing help with the output.
The prompt is to write a general code that evaluates a polynomial (ex: 5x^4+3x^3+2x^2). The instructions say that I have to use an array of coefficients in which the size of the array is the inputted degree "n". The user then has to input a value of x then solve the value for each individual polynomial and add it all together.
Here is my code so far:
import java.util.Scanner;
public class GenPol {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String AnsPol = "yes";
while(AnsPol.equals("yes")) {
System.out.println("Please enter the largest degree of polynomial");
int n = in.nextInt();
if((n>0 || n==0)) {
double[] x = new double[n+1];
int arrayLength = x.length;
for(int degreeLength=0; degreeLength<=arrayLength; degreeLength++){
double totalVal=0; //overall accumulator
double indiV =0; //individual accumulator
for(int i=0; i<=arrayLength; arrayLength--) {
System.out.println("Please enter the coefficient for
degree " + arrayLength + ":");
double coefficient = in.nextDouble();
indiV=coefficient;
}
System.out.println("Please enter the value for x: ");
double xVal = in.nextDouble();
double xPowered = Math.pow(xVal, degreeLength);
double indivVal = indiV*xPowered;
x[degreeLength] = indivVal; //store this value into this
element
totalVal += x[degreeLength]; //add the elements together
String XAns = "yes";
while(XAns.equals("yes")) {
System.out.println("The total value is " + totalVal);
System.out.println("Would you like to evaluate another
value of x?");
XAns = in.nextLine();
}
}
} else{
System.out.println("Please enter a degree that's greater than or
equal to 0.");
}
}
}
}
This is the output when I did a test run:
Please enter the largest degree of polynomial
3
Please enter the coefficient for degree 4:
3
Please enter the coefficient for degree 3:
1
Please enter the coefficient for degree 2:
2
Please enter the coefficient for degree 1:
2
Please enter the coefficient for degree 0:
1
Please enter the value for x:
2
The total value is 1.0
Would you like to evaluate another value of x?
Please enter the largest degree of polynomial
Can someone point me to the right direction in terms of my iteration? I'm not entirely sure why my total value keeps outputting 1.0. And also if my loops are properly placed?
Thank you so much!!

First to make things easier for you i'd recommend creating one loop in the main method. have it call getInput(), calc(), displayResults() and do those jobs in those methods. Second what is going on here (n>0 || n==0)? use n>=0 . third... your main problem lies here
for(int i=0; i<=arrayLength; arrayLength--) {
System.out.println("Please enter the coefficient for
degree " + arrayLength + ":");
double coefficient = in.nextDouble();
indiV=coefficient;
}
if you're still unable to figure it out post and get more hints.

Related

I think my program is giving an inaccurate result for Riemann Sums

this is my first post here!
So, as an extra credit project for my Calculus course, the professor offered us an opportunity to write a simple program that calculates the area under a user specified curve. I realize this isn't the best way to implement this, but he say's that's fine, but I think this is giving me the wrong answer. Could anyone help?
import java.util.*;
public class RiemannSum2 {
public static void main(String args []) {
System.out.println("This is a Riemann Sum Calculator. This calculator accepts polynomials in the form of a(x)^ex + b(x)^ex2 + c, where c is a constant.");
System.out.print("Enter the first coeffecient of the polynomial: ");
Scanner sc = new Scanner(System.in);
int firstCoe = sc.nextInt();
System.out.print("Enter the exponent of the first term: ");
int firstExp = sc.nextInt();
System.out.print("Enter the second coeffecient of the polynomial: ");
int secondCoe = sc.nextInt();
System.out.print("Enter the exponent of the second term: ");
int secondExp = sc.nextInt();
System.out.print("Enter the third term of the polynomial: ");
int thirdTerm = sc.nextInt();
System.out.print("Enter the x value that you want to start the Riemann Sum: ");
int startX = sc.nextInt();
System.out.print("Enter the x value to stop the Riemann Sum: ");
int endX = sc.nextInt();
String poly = (firstCoe+"x^"+firstExp+"+"+secondCoe+"x^"+secondExp+"+"+thirdTerm);
System.out.println("Your polynomial is: "+poly);
System.out.print("Enter the number of rectangles you want: ");
int rectangles = sc.nextInt();
double numerator = (endX-startX);
double rectanglesD = (double)rectangles;
double constantWidth = numerator/rectanglesD;
System.out.println("This is the constant width: " + constantWidth);
double totalSum = 0;
//System.out.println(totalSum);
for(int i = 0; i < rectangles ; i++) {
totalSum = totalSum+((Math.pow((firstCoe * (i/constantWidth)), firstExp)) + (Math.pow((secondCoe * (i/constantWidth)), secondExp))+thirdTerm);
}
totalSum = totalSum*constantWidth;
System.out.println("The Riemann Sum of your polynomial is roughly equivalent to: "+ totalSum);
}
}
You use (i/constantWidth) to calculate the argument of your function (x). However, it should be
double x = startX + i * constantWidth;
Furthermore, your coefficients should be outside of the pow function. Otherwise, they will get exponentiated too. Removing some of the superfluous parentheses makes the formula a lot easier to read. Like this:
double x = startX + i * constantWidth;
totalSum = totalSum
+ firstCoe * Math.pow(x, firstExp)
+ secondCoe * Math.pow(x, secondExp)
+ thirdTerm;
Unrelated to the code: Since you have a simple polynomial, you can calculate the antiderivative analytically and simply evaluate that function instead.

Java program gives incorrect Taylor series term for function e^x

//java program that asks the user to input a number that e^x=1+x+x^2/2! +x^3/3!... e is a mathematical constant equal to 2.718...
import java.util.Scanner;
public class taylor_2 {
public static void main(String args[]) {
Scanner input=new Scanner(System.in);
double x; //input for x
double factorial=1; //initializes factorial
int counter=1; //initializes counter
double result=1; //initializes result
System.out.println("Enter non negative number"); //asks user to enter x
x=input.nextInt();
//output in while loop will continue to be generated if user doesn't entered a negative number
while(x<1){
System.out.println("I said entered a positive number");
x=input.nextInt();
}
while(x>counter){
factorial=factorial*counter;//factorial formula
result=result+(Math.pow(x,counter))/factorial; //equation for e^x=1+x+x^2/2! +x^3/3!
counter++;
}
System.out.println("Taylor series is " +result);//output for taylor equation e^x
}
}
Here is the output of my code:
Enter non negative number
2
Taylor series is 4.0
When I entered 2 , it should have outputted 7.3890560983 instead of 4.0 since e=2.718... and e^2=7.3890560983. What am I doing wrong?
The problem is that the Taylor series is not the same function that e^x.
It will return a function that is close to the function e^x.
For understanding it better, I recommend you to look the second picture of the next link:
https://en.wikipedia.org/wiki/Taylor_series
You can see in the previous picture that as n is getting larger the function is getting more accurate.
Your code's problem is that your x value is your n value, and this is not really true.
x: Must be the value you want to now e^x.
n: Is the accurate of your equation. Larger means more accurate.
So you must change while(x>counter) with while(n>counter), where n can be either a variable with the user selected accuracy, or a constant with your selected accurcy.
I think that until x=100, n=150 should work.
I hope that helps you! :)
There seems to be an answer here: EXP to Taylor series for c++, even though the algorithm is slightly different to yours. Here's its Java version:
public class TaylorSeries {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("Enter x:");
double x = input.nextDouble();
double result = calcExp(x);
System.out.println("calcExp(x) = " + result);
System.out.println(" e^x = " + Math.pow(Math.E, x));
}
static double calcExp(double x) {
double eps = 0.0000000000000000001;
double elem = 1.0;
double sum = 0.0;
boolean negative = false;
int i = 1;
sum = 0.0;
if (x < 0) {
negative = true;
x = -x;
}
do {
sum += elem;
elem *= x / i;
i++;
if (sum > Double.MAX_VALUE) {
System.out.println("Too Large");
break;
}
}
while (elem >= eps);
return negative ? 1.0 / sum : sum;
}
}
The output:
Enter x:
2
calcExp(x) = 7.389056098930649
e^x = 7.3890560989306495
All credit should go to the answer here: EXP to Taylor series. I have only converted c++ code to Java

Java how to compute average scores using loops

I need to write a program in Java that computes the average score for 4 students. The student will put in their 4 scores, and once they are done they will input -1 to compute the average. Once this is done the program needs to move onto student 2 and so on. At the end it is supposed to display the highest average from the 4 student average test scores. Here is what it should look like when it is run:
Student 1
Enter your score: 100
Enter your score: 90
Enter your score: 80
Enter your score: 70
Enter your score: -1 * once the student enters -1 it should compute average
Average Score = 85.
Student 2
Enter your score: 90
ETC
ETC
The problem with my code is that the average is only correct for the first student. When I input -1 to get the average for the second student, the calculation is incorrect. We are only allowed to use loops. The only hints I was given were that we are supposed to write an outer loop that iterates 4 times, write an inner loop that loops as long as the student has scores to enter, inside the inner loop prompt the user to enter their last score or -1 to compute average. I don't want you guys to do the project for me but to just set me in the right direction. I feel like I am not using the right loop.
import java.util.Scanner;
public class TestScore
{
public static void main(String[]args)
{
double score = 0;
double totalScore = 0;
double count = 0;
double average = 0;
Scanner input = new Scanner(System.in);
System.out.println("Student 1");
System.out.printf("Enter Your Score: ");
score = input.nextDouble();
while (score != -1){
System.out.printf("Enter Your Score: ");
totalScore = totalScore + score;
score = input.nextDouble();
count++;
average = totalScore / count;
if (score == -1){
System.out.printf("Average Score = %.2f\n ",average);
count = 0;
score = 0;
totalScore = 0;
average = 0;
System.out.println("Student 2");
System.out.printf("Enter Your Score: ");
score = input.nextDouble ();
count++;
average = totalScore / count;
}
}
}
}
You haven't explicitly asked a question so I'll try and comply to the "set me in the right direction" part.
I'd suggest re-formatting the loop structure to a cleaner one, like this:
double total;
for(int student = 1; student <= 4; student++) {
System.out.printf("Student %d\n", student);
double sum = 0, count = 0;
while(true) {
System.out.printf("Enter your score: ");
double input = scanner.nextDouble();
if(input == -1) break;
sum += input;
count++;
}
total += sum;
System.out.printf("Average: %.2f\n", sum / count);
}
System.out.printf("Total: %.2f\n", total);
Hope that's enough to give you some pointers.
edit: forgot to take care of total
So, you wish to iteratively go through all the input and just remember the maximum one. Make an integer variable max and after each student, just change it if needed. (It's zero by default jn Java)
As for the calculation for each student, you shouldn't be checking for the failed " score != - 1" condition in each iteration. Instead, you should do the final calculations after the while loop. (average, possible update of the maximum, resetting the variables, etc. )
You also need the outer loop (in the stated code, these calculations are done for one student only) which you would control in a different manner.
Also, if you need to use only 4 grades, you might want to consider using the for loop.
You can try with this :D
public static void main (String[] args) throws java.lang.Exception
{
double average = 0;
double i = 0;
int student = 0;
boolean flag = true;
Scanner input = new Scanner(System.in);
while(flag)
{
System.out.printf("Student: ");
System.out.println(student);
System.out.print("Enter Your Score: ");
double score = input.nextDouble();
if(score!=-1){
average=average+score;
i=i+1;
}
if(score==-1){
System.out.printf("Average: ");
System.out.println(average/i);
//reset values
average = 0;
i = 0;
student=student+1;
}
if(score==-2){
//you need break the while in some moment.
flag = false;
}
}
}

Java - Using for loop to average set of grades read in from keyboard

First time poster here. I'm aware of the negative stigma carried with asking for help on homework assignments, however I believe this would be an exception as this is an intro course and the professor stated specifically to use Google to find examples of for loops in Java (of which we have yet to even cover in class). I have absolutely no Java experience and would really appreciate any feedback:
Program asks user how many grades there are.
Program asks user for each grade (for loop needed and should sum grades within loop).
Take sum of all grades, compute average and store in a float variable grade.
Print grade value to console and append a number to a string such as "Grade Average is: " + grade
Example should read as:
Enter number of grades: 2
Enter grade: 90
Enter grade: 81
Grade Average is: 85.5
My code so far (not much here):
// This program computes the letter grades for number of grades given by user
import java.util.*;
public class GradeAverage
{
public static void main(String[] args)
{
int count;
float sum = 0;
float grade;
Scanner scan = new Scanner(System.in);
}
}
Edit:
// This program computes the letter grades for number of grades given by user
import java.util.*;
public class GradeAverage
{
public static void main(String[] args)
{
int count;
float sum = 0;
float grade;
Scanner scan = new Scanner(System.in);
System.out.print("Enter number of grades: ");
count = scan.nextInt();
for (int i = 0; i < count; ++i)
System.out.print("Enter grade " + (i + 1) + ": ");
grade = scan.nextFloat();
sum += grade;
System.out.println("The average of the grades is: " + sum/count);
}
}
This is what I have now, however a test displays incorrect results (example):
Enter number of grades: 2
Enter grade 1: Enter grade 2: 50 50
The average of the grades is: 25.0
Each grade needs to be entered on separate lines so the averaging is skewed as a result.
import java.util.Scanner;
public static void main(String[] args) {
int count = 0;
float sum = 0;
float grade = 0;
Scanner scan = new Scanner(System.in);
System.out.print("Enter number of grades: ");
count = scan.nextInt();
for (int i = 0; i < count; i++) {
System.out.print("Enter grade no " + (i + 1) + " : ");
grade = scan.nextFloat();
sum += grade;
}
System.out.println("Sum = " + sum);
System.out.println("Average = " + sum / (float) count);
}
Break the big task into smaller tasks , like #user2864740 said , write the algorithm (not code) on a paper then start translating that to code
u reached the part where u created a scanner to read input , now read the input and ....figure out the rest .
To learn how to read user input read this.
To learn how to make an integer out of Strings ur scanning read this
the rest is basic math really , read your textbook , and good luck ;)
edit : at least come out with some algorithm then maybe we'll help with the code
I won't solve the homework for you, I will help you however:
How to use a for loop:
for (int i = #startValue#; #booleanCondition#; #runTheFollowingCodeAtEachIteration#)
{
//code
}
ex:
for(int i = 0; i<10; i++)
{
System.out.println(i);
}
will display:
0
1
2
3
4
5
6
7
8
9
Your homework:
Program asks how many grades there are:
Scan a value called NumberOfGrades (called count in your code) inputted by the user.
Program asks user for each grade + sums the grades:
Use a for loop, with a starting value of i, and a upper limit of NumberOfGrades. Scan each grade and add it to a value called GradeSum, which initially should be 0 before entering the for loop.
Print value to console... :
Divide GradeSum by NumberofGrades, and display it how you would like it to be displayed.
Tips:
-Use System.out.print("\nEnter grade: "); in your for loop before each scan.
To avoid directly answering your homework question (which both won't help you get it and is probably not allowed), let's start with "what is a for loop?"
A for loop is a fancy loop that does the following things for you:
Initializes one (or more) variables to initial values the first time the loop statement is executed
Each iteration, checks a boolean condition to determine if it should loop again. If the expression evaluates to true, iterate again. Otherwise, break the loop and continue with the code following the loop.
A statement that is run each time the loop finishes iterating.
For example, the following loop would print the numbers 1 .. 10.
for(int i = 1; i <= 10; i++){
System.out.println(i);
}
The first part of the loop statement int i = 1 is the initialization block. i is initialized to an int with value 1 when the for loop is executed for the first time.
The second part of the loop statement i <= 10 is the boolean condition to check to determine if another iteration is required. In this case, i <= 10 evaluates to true if i is less than or equal to 10, and false once i hits 11 (or any larger number).
Finally, the third part i++ is the statement run when the for loop finishes an iteration. i++ adds 1 to the current value of i, thus i will increase in value by 1 each iteration.

How to do an addition from random numbers by the user?

I am new to Java and I would like some help. I have to solve this problem and I have it almost 90% solved:
Prompt the user to enter number of students. It must be a number that is perfectly divisible by 10 i.e. (number % 10) = 0
Check user input. If user input is not divisible by 10, keep asking the user for input until he enter a right number.
Accept user input and generate that many random numbers in the range from 0 to 100.
Print a matrix of random numbers and calculate the sum and average of all these random numbers and print them to the user.
Format sum and average to three decimal points.
This is my code so far:
import java.text.DecimalFormat;
import java.util.Scanner;
public class Calculator10 {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
int num;
do {
System.out.print("Enter a number: ");
num = user_input.nextInt();
} while(num % 10 != 0);
double numb;
DecimalFormat dec = new DecimalFormat("0.00");
for (int i=0; i<num; i++){
numb = Math.abs(Math.random() * ( 0 - 100 ));
System.out.print(" " +dec.format(numb) + " ");
}
}
}
As you can see, I have solved until the first part of # 4. I am not sure how I could sum all those random numbers displayed on the screen after user input. Of course, we have to store them in an array but I tried to do that but couldn't. So, how could I complete step #4 and 5? I would appreciate any help. Thanks a lot guys.
Here is how you should do it:
import java.text.DecimalFormat;
import java.util.Scanner;
public class Calculator10 {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
int num;
do {
System.out.print("Enter a number: ");
num = user_input.nextInt();
} while(num % 10 != 0);
double numb;
double sum=0;
DecimalFormat dec = new DecimalFormat("0.00");
for (int i=0; i<num; i++){
numb = Math.random() * ( 100 - 0));
System.out.print(" " + dec.format(numb) + " ");
sum += numb;
}
System.out.println("The sum is: " + dec.format(sum));
System.out.println("The average is:" + dec.format(sum/num));
}
}
Please note that I have slightly changed the way you were generating the random numbers which obviates the need to use Math.abs(). Also see the following answer to see how to generate random numbers between two different values:
Generating random numbers with Java
You do not need to store them in an array. Just declare int sum = 0 at the start and do sum += numb each time you generate a random number. Also, you are generating random numbers in a strange way. Take a look at the java.util.Random class.

Categories