How to work with an 'x' variable like in math? - java

How can I work with an 'x' variable like in math?
I need to write a code that determines a polynomial function. For example if the input data is 2, 4, 8, 9 then the function would be 2 + 4x + 8x^2 + 9x^3.
Now I do know how to process the input data etc. but I don't know how to declare a variable that has no value, for example I declared a variable x = double, but I still have to initialize it but I don't want to give x a value at this point yet?
So how can I write a method that for example returns 'x' to the power of something?
This is what I have at the moment (it still doesn't work of course)
public class Interpol {
public static void main(String []args) {
Scanner scanner = new Scanner(System.in);
//get user input (polynomial coefficients and interval values x1 and x2)
ArrayList<Double> polynomialCoefficients = new ArrayList<Double>();
int amountCoefficients = 0;
while (scanner.hasNextDouble()) {
polynomialCoefficients.add(scanner.nextDouble());
amountCoefficients++;
}
String in = scanner.next();
double x1 = scanner.nextDouble();
double x2 = scanner.nextDouble();
//call method f to determine the polynomial function
double x;
double[] termsFunction = new double[amountCoefficients];
for (int i = 0; i < polynomialCoefficients.size(); i++) {
termsFunction[i] = f(i, polynomialCoefficients.get(i));
}
//call method findaroot to determine the root
//print result
}
//determine function of which a root is to be found
public static double f(int i, double polynomialCoefficient) {
if (i == 0) {
return polynomialCoefficient;
}
double x;
return polynomialCoefficient * (Math.pow(x, i));
}
/* //rounds off d to 3 decimals
public static double rnd(double d) {
}
//returns a root in this interval, recursive function
public static double findaroot{double x1, double x2) {
}*/
}

You need to make a Class of objects that represent polynomials. The class will store the coefficients in an instance variable, and provide a method to evaluate the polynomial at a given value.
import java.util.*;
public class Foo {
public static void main(String[] args)
throws Exception
{
Scanner scanner = new Scanner(System.in);
//get user input (polynomial coefficients and interval values x1 and x2)
ArrayList<Double> polynomialCoefficients = new ArrayList<Double>();
int amountCoefficients = 0;
while (scanner.hasNextDouble()) {
polynomialCoefficients.add(scanner.nextDouble());
amountCoefficients++;
}
Polynomial polynomial = new Polynomial(polynomialCoefficients);
String in = scanner.next();
while (scanner.hasNextDouble()) {
double x = scanner.nextDouble();
System.out.println("f(" + x + ") = " + polynomial.evaluate(x));
}
}
static class Polynomial {
ArrayList<Double> _coefficients;
public Polynomial(ArrayList<Double> coefficients) {
_coefficients = coefficients;
}
public double evaluate(double x) {
double result = 0;
// This algorithm is called Horner’s rule. See Knuth.
for (int i = _coefficients.size() - 1; i>= 0; i--) {
result *= x;
result += _coefficients.get(i);
}
return result;
}
}
}
If I run this program and type 2 4 8 9 x 2.7, then it prints f(2.7) = 248.267, which is correct according to Wolfram Alpha.

Related

How to properly output arcsin, and solve this math task?

I'm doing my HW for Java clas, and I can't understand how am I able to output this task properly and solve it. User have to input the X value.
package lab1;
import java.util.Scanner;
public class Lab1 {
public static void main (String [ ] args) {
System.out.println("Input x: ");
Scanner scan = new Scanner(System.in);
double x = scan.nextInt();
double c = Math.pow(x, 2);
// x в квадрате
double a = Math.pow((3+x),6);
//3+х в степени 6
double b = Math.pow(Math.E,0);
//експонента
double v = Math.log(x);
double n = Math.asin(c);
double K = Math.sqrt((a - v) / b + n));
System.out.println("Your answer - " + K);
}
}
https://imgur.com/a/S4iSpO2
I need prog to solve this task when user input the x value
P.S I know It's very stupid question and easy task, but I'm just getting started with dev so I hope you'll understand)
If I understand you correctly you want to merge step by step the individual terms of the formula. Something like below should work. But note that the arcsin is defined in the range [-π/2, π/2]. Since you even have the factor 6 in there, your program only returns useful values for x values between [-0.4,0.4]
code
public class Lab1 {
public static void main(String[] args) {
System.out.println("Input x: ");
Scanner scan = new Scanner(System.in);
double x = scan.nextDouble();
// (3+x)^6
double a = Math.pow(3+x, 6);
// lnx
double b = Math.log(x);
// √(3+x)^6 - lnx
double c = Math.sqrt(a-b);
//e^0 [something^0 is always = 1, so you could also set it just to 1]
double e = Math.pow(Math.E, 0); //double e = 1;
//arcsin6x^2
double f = Math.asin(6 * Math.pow(x, 2));
double k = c / (e+f);
System.out.println("Your answer: " + k);
}
}

How to call on a method in Java

import java.util.Scanner;
public class Question1
{
public static void main(String[] args)
{
Primary test = new Primary();
test.Main();
}
}
class Primary
{
double x;
double y;
double z;
double Small;
double Avg;
int dad;
final int userNumbers = 3;
Scanner in = new Scanner(System.in);
public void Main()
{
System.out.println("Please enter 3 numbers");
x = in.nextInt();
y = in.nextInt();
z = in.nextInt();
Primary test = new Primary();
test.Smallest();
test.Average();
System.out.println("The average of the numbers is:" + Avg);
System.out.println("The smallest of the numbers is:" + Small);
}
public void Smallest()
{
if(z < y && z < x)
Small = z;
if (x < z && x < y)
Small = x;
if (y < z && y < x)
Small = y;
}
public void Average()
{
Avg = x + y + z / userNumbers;
}
}
I have no clue what to do since everything ive tried either gives me an error or I'm just not doing it right. I'm not even sure I'm doing what the professor is asking me to do, and he never responds to his emails. If anyone could help me it would be greatly appreciated (And if I'm not doing what my professor is asking please let me know).
Heres his instructions + The assignment on page 248
Around Page 248. Practice Exercise E5.1.You will create one class that has three methods: main(), smallest(), and average(). main() reads the test data values and prints the results. You may want to do this in a loop. smallest() and average() do not read data values or print the results. The main() method reads the data values and prints the results.
Write the following methods and provide a program to test them.
a. double smallest(double x, double y, double z), returning the smallest of the arguments
b. double average(double x, double y, double z), returning the average of the arguments
Here try this....`
let me know how that works
import java.util.ArrayList;
import java.util.Scanner;
package javaapplication17;
public class Question1 {
public static void main(String[] args)
{
double avg, small;
Scanner in = new Scanner(System.in);
System.out.println("Please enter 3 numbers");
double x = in.nextInt();
double y = in.nextInt();
double z = in.nextInt();
//Method calls -----------------------------------
avg = average(x, y, z);
small = smallest(x, y, z);
//Method calls -----------------------------------
System.out.println("The average of the numbers is: " + avg);
System.out.println("The smallest of the numbers is: " + small);
}
public static double smallest(double x, double y, double z)
{
double small = 0;
if(z <= y && z <= x)
small = z;
if (x <= z && x <= y)
small = x;
if (y <= z && y <= x)
small = y;
return small;
}
public static double average(double x, double y, double z)
{
return (x + y + z) / 3.0;
}
}
You do need to learn java to do this. See https://en.wikiversity.org/wiki/Java_Tutorial/Hello_World! and others like it for hints.
To answer the question given to you, you only need one class - you have two. In that class, you need three methods. Two of the methods return values - you have them returning a void. You shouldn't need any field variables in your class.
Structure the class as in the tutorial link. (This isnt' a working answer - you still have to do the homework.)
public class Question1 {
public static void main( String[] args ) {
double x, y, z;
// Add your a loop here to collect your x, y and z
// data and process it
while (true) {
// Collect the data ...
// Call the methods
double smallest = smallest(x, y, z);
double average = average(x, y, z);
// Do something with the results
}
}
public static double smallest(double x, double y, double z) {
double smallValue;
// Add your logic and set smallValue
return smallValue;
}
public static double average(double x, double y, double z) {
// Calculate the average and return that value
// as in the smallest method...
}
}
To test the functions, write another program like the following:
import Question1;
public class TestQuestion1 {
public static void main( String[] args ) {
// Add test code here. Something like
double result = Question1.smallest(1.0, 2.0, 3.0)
// Check that the result is 1.0
// Add other tests - output the results
}

After a while loop: Why is an array that was just written to empty?

We're currently trying to implement the kmeans algorithm in java. Our problem is this:
We're using the getData() method to fill a two dimensional array with data from a file. Inside the while loop in the getData() method we have a println() and we have another one right before the return command.
The first println() gives us the correct values we've just gotten from the file.
The second println() just gives us 0.0 for every field inside that array, except for arrayList[299][0].
Why is that?
class KMeans {
// Number of clusters
int numberOfClusters = 4;
// Starting point for each cluster (these values should be better than completely random values for our given data set)
static double[] a = new double[]{-1.5, 2.0};
static double[] b = new double[]{-1.5, 7.0};
static double[] c = new double[]{1.5, 7.0};
static double[] d = new double[]{1.5, 2.0};
static double[][] pointArray;
// This calculates the distance between a given point from the data set and a centroid
public static double calculateDistance(double[] point, double[] centroid) {
// get difference for X coordinates
double maxX = Math.max(point[0], centroid[0]);
double minX = Math.min(point[0], centroid[0]);
double differenceX = maxX - minX;
double differenceXSquared = Math.pow(differenceX, 2);
// get difference for Y coordinates
double maxY = Math.max(point[1], centroid[1]);
double minY = Math.min(point[1], centroid[1]);
double differenceY = maxY - minY;
double differenceYSquared = Math.pow(differenceY, 2);
// The whole thing is nothing other than pythagoras
double zSquared = differenceXSquared + differenceYSquared;
double z = Math.sqrt(zSquared);
return z;
}
// This calculates which of the given distances is the lowest
public static double[] nearestCluster(double e, double f, double g, double h) {
double x = Math.min(e, f);
double y = Math.min(x, g);
double z = Math.min(y, h);
if (z == e) {
return a;
}
if (z == f) {
return b;
}
if (z == g) {
return c;
} else {
return d;
}
}
// Read the file
public static double[][] getData() {
try (BufferedReader br = new BufferedReader(new FileReader("/home/john/Downloads/data.txt"))) {
String line;
int i = 1;
int j = 0;
while ((line = br.readLine()) != null) {
// Create the array in which we store each value
pointArray = new double[i][4];
//Splits each line a the space and writes it to an array
String[] split = line.split("\\s+");
// Cast the strings to double and write them to our pointArray
pointArray[j][0] = Double.parseDouble(split[0]);
pointArray[j][1] = Double.parseDouble(split[1]);
System.out.println(pointArray[0][0]);
i++;
j++;
}
} catch (IOException e) {
}
System.out.println(pointArray[0][0]);
return pointArray;
}
public static void main(String[] args) throws FileNotFoundException, IOException {
pointArray = getData();
for (double[] x : pointArray) {
double distanceA = calculateDistance(x, a);
double distanceB = calculateDistance(x, b);
double distanceC = calculateDistance(x, c);
double distanceD = calculateDistance(x, d);
// Assigns the closest cluster to each point (not too efficent because we call the function twice, but it works)
x[2] = nearestCluster(distanceA, distanceB, distanceC, distanceD)[0];
x[3] = nearestCluster(distanceA, distanceB, distanceC, distanceD)[1];
}
}
}
The line
pointArray = new double[i][4];
reinitializes the array each time through the loop. In effect you're throwing away every value except the last line that you read.
Instead, use an ArrayList to hold each individual line. Set it up before the while loop like this:
List<Double[]> pointList = new ArrayList<>();
Then you can add to it at each line like this:
Double[] points = new Double[4];
// ...
points[0] = Double.parseDouble(split[0]);
// etc.
pointList.add(points);
Then either return pointList or convert it to an array for return.

Generate Natural Logarithm of 2 Customly

I know I could generate it using Math.log(2) but I when I try to make up my own program to generate a natural log of 2 it continuously print 1. This is my code:
import java.math.BigDecimal;
import java.util.Scanner;
public class Ques11 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
BigDecimal sum = new BigDecimal(1);
for(int i = 2; i <= n; i++) {
sum.add(new BigDecimal(1/n));
}
System.out.print(sum.setScale(10).toPlainString());
}
}
I have tried to use float, double and int and in the end used BigDecimal but I still got 1 as the result I don't know why.
P.S It actually throws InputMismatchException when big numbers are given i.e greater than 2000000000 or 2 Billion.
n is defined as an int and 1 is an int literal. When you divide two ints you use integer arithmetic, which would return only the whole part of the fraction - in your case, 0.
To rectify this, you should use doubles:
public class Ques11 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
double d = scan.nextInt(); // Note we're assigning to a double
BigDecimal sum = new BigDecimal(1);
for(int i = 2; i <= d; i++) {
sum.add(new BigDecimal(1.0/d));
}
System.out.print(sum.setScale(10).toPlainString());
}
}

Using loops to compute factorial numbers, Java

I'm trying to compute the value of 7 factorial and display the answer, but when I tried to look up a way to do this I kept finding code that was written so that a number first had to be put in from the user and then it would factor whatever number the user put in. But I already know what number I need, obviously, so the code is going to be different and I'm having trouble figuring out how to do this.
I tried this at first
public class Ch4_Lab_7
{
public static void main(String[] args)
{
int factorial = 7;
while (factorial <= 7)
{
if (factorial > 0)
System.out.println(factorial*facto…
factorial--;
}
}
}
But all it does is display 7*7, then 6*6, then 5*5, and so on, and this isn't what I'm trying to do.
Does anyone know how to do it correctly?
import java.util.Scanner;
public class factorial {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
//Gives Prompt
System.out.print("Enter a number to find the factorial of it");
//Enter the times you want to run
int number = input.nextInt();
//Declares new int
int factor = 1;
//Runs loop and multiplies factor each time runned
for (int i=1; i<=number; i++) {
factor = factor*i;
}
//Prints out final number
System.out.println(factor);
}
}
Just keep multiplying it and until it reaches the number you inputted. Then print.
Input:5
Output:120
input:7
Output:5040
You need to have two variables, one for the factorial calculation and other for the purpose of counter. Try this, i have not tested it but should work:
public static void main(String[] args)
{
int input = 7;
int factorial = 1;
while (input > 0)
{
factorial = factorial * input
input--;
}
System.out.println("Factorial = " + factorial);
}
int a=7, fact=1, b=1;
do
{
fact=fact*b;//fact has the value 1 as constant and fact into b will be save in fact to multiply again.
System.out.print(fact);
b++;
}
while(a>=b); // a is greater and equals tob.
1st reason:
The methods you seen are probably recursive, which you seem to have edited.
2nd:
You are not storing, ANYWHERE the temporal results of factorial.
Try this
//number->n for n!
int number = 7;
//We'll store here the result of n!
int result = 1;
//we start from 7 and count backwards until 1
while (number > 0) {
//Multiply result and current number, and update result
result = number*result;
//Update the number, counting backwards here
number--;
}
//Print result in Screen
System.out.println(result);
Try this:
public static void main(String args[]) {
int i = 7;
int j = factorial(i); //Call the method
System.out.println(j); //Print result
}
public static int factorial(int i) { //Recursive method
if(i == 1)
return 1;
else
return i * factorial(i - 1);
}
This would print out the factorial of 7.
public class Factorial {
public static void main(String[] args) {
int result = factorial(5); //this is where we do 5!, to test.
System.out.println(result);
}
public static int factorial(int n) {
int x = 1;
int y = 1;
for (int i = 1; i <= n; i++) {
y = x * i;
x = y;
}
return y;
}
}
/*so, for 3! for example, we have:
i=1:
y = x * i, where x = 1, so that means:
y = 1*1 ; y= 1; x = y so x = 1. Then i increments =>
i = 2:
y = x * i. x is 1 and i is 2, so we have y = 2. Next step in code: x=y, means x = 2. Then i increments =>
i = 3:
y = x *i so we have y = 2*3. y=6. */

Categories

Resources