Lagrange interpolation in JAVA - java

I have done a search around, but there isnt any code available in java hence I have write my own and I have encountered some issue. I actually got this code from a c++ source and trying hard to convert it into a workable java program.
http://ganeshtiwaridotcomdotnp.blogspot.sg/2009/12/c-c-code-lagranges-interpolation.html
public static void main(String[] args) {
int n;
int i, j;
int a;
int x[] = null;
int f[] = null;
int sum = 0;
int mult;
Scanner input = new Scanner(System.in);
System.out.println("Enter number of point: ");
n = input.nextInt();
System.out.println("Enter value x for calculation: ");
a = input.nextInt();
for (i = 0; i < n; i++) {
System.out.println("Enter all values of x and corresponding functional vale: ");
x = input.nextInt();
f = input.nextInt();
}
for (i = 0; i <= n - 1; i++) {
mult = 1;
for (j = 0; j <= n - 1; j++) {
if (j != i) {
mult *= (a - x[j]) / (x[i] - x[j]);
}
sum += mult * f[i];
}
}
System.out.println("The estimated value of f(x)= " + sum);
}

For Lagrange Interpolation Formula -
You should use double data type Array
Your should make Arrays with specific number of items
Look at the program below, you will understand.
double product, sum = 0;
Scanner sc = new Scanner(System.in);
System.out.print("Enter the Number of Terms: ");
int n = sc.nextInt();
double[] x = new double[n];
double[] y = new double[n];
System.out.println("Enter all the x, y terms: ");
for (int i = 0; i < n; i++) {
x[i] = sc.nextDouble();
y[i] = sc.nextDouble();
}
System.out.println("x = {" + Arrays.toString(x) + "}");
System.out.println("x = {" + Arrays.toString(y) + "}");
System.out.print("Enter a point to Find it's value: ");
int xPoint = sc.nextInt();
// End of inputs
product = 1;
// Peforming Arithmatic Operation
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (j != i) {
product *= (xPoint - x[j]) / (x[i] - x[j]);
}
}
sum += product * y[i];
product = 1; // Must set to 1
}
System.out.println("The value at point " + xPoint + " is : " + sum);
// End of the Program
}
}

int x[] = null;
int f[] = null;
...
for (i = 0; i < n; i++) {
....
x = input.nextInt();
f = input.nextInt();
}
Looks clear enough. Simply create array instance for x and f:
x = new int[n];
f = new int[n];
Somewhere after:
n = input.nextInt();
Before above for loop, and modify the for body:
...
x[i] = input.nextInt();
f[i] = input.nextInt();

public static void main(String[] args) {
System.out.println("Langrages");
Scanner sc = new Scanner(System.in);
System.out.println("Enter the no of terms: ");
int n = sc.nextInt();
float[] ax = new float[n];
System.out.println("Enter values of x");
for(int i=0 ;i<n;i++) {
ax[i] = sc.nextFloat();
}
float[] ay = new float[n];
System.out.println("Enter values of y");
for(int i=0 ;i<n;i++) {
ay[i] = sc.nextFloat();
}
System.out.println("Enter the value of x\n at which you find y");
int x = sc.nextInt();
float num,den;
float term =0;
for(int i=0;i<n;i++) {
num=1;
den=1;
for(int j=0;j<n;j++) {
if(j!=i) {
num=num*(x-ax[j]);
den = den*(ax[i]-ax[j]);
}
}
term += (num/den)*ay[i];
}
System.out.println(term);
sc.close();
}

Related

Having trouble searching array

So I have everything working fine up until the point in which I need to search. I'm really new to this so my code is probably awful I'm sorry in advance. Anyway, its a user input array, and the user should be able to search for a number in an array. Im getting the error for a duplicate variable on line 50 (int i, get 1).
import java.util.Scanner;
class SearchingSorting {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
System.out.println ("How many numbers would you like to input?");
int num = input.nextInt();
double[] array = new double[num];
for (int i = 0; i < num; i++) {
System.out.println ("Input number " + (1 + i) + ":");
array[i] = input.nextDouble();
}
for (double temp1 : array){
System.out.print (temp1 + "\t");
}
input.close();
int pass;
int i;
int hold;
for(pass = 1; pass < array.length; pass++)
{
for(i = 0; i < array.length - 1; i++)
{
if(array[i] > array[i+1])
{
hold = (int) array[i];
array[i] = array[i+1];
array[i+1] = hold;
}
}
System.out.println("\nSorted number is: ");
for(i = 0; i < array.length; i++)
System.out.print(" " + array[i]);
}
int i, get1;
Scanner keyboard = new Scanner(System.in);
int[] numbers = new int[10];
for(i = 0; i < numbers.length; i++)
{
numbers[i] = i * 10;
}
System.out.print("Enter search number: ");
get1 = keyboard.nextInt();
SearchMethod(numbers, get1);
}
public static void SearchMethod(int[] num, int get2)
{
int i ;
boolean j = false;
for(i = 0; i < num.length; i++)
{
if(num[i] == get2)
{
j = true;
break;
}
}
if(j == true)
System.out.println(get2 + " is found at num[" + i + "]");
else
System.out.println(get2 + " is not found in an array");
}
}
You are trying to declare a new variable with the same name ("i") in the same scope.
Rename your variable i on line 50.

How to initialize variable back to 0 in a while loop in java?

I want my code to loop, but reinitialize the variable back to 0. Every time I input a number, it add it to the previous result, but I want it to reset. I attached two images below. One is the actual output and the other is the expected output.
import java.util.Scanner;
public class AddOrMultiplyNNumbers {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String am;
int sum = 0;
int total = 1;
int n = 0;
while (true) {
System.out.print("enter an integer number: ");
n = input.nextInt();
if(n == 0) {
break;
}
System.out.print("enter either 'a' or 'm': ");
input.nextLine();
am = input.nextLine();
if (am.equals("a")) {
for (int y = 1; y <= n; y++) {
sum = sum + y;
}
System.out.println(sum);
} else if (am.equals("m")) {
for (int x = 1; x <= n; x++) {
total = total * x;
}
System.out.println(total);
}
}
}
}
Actual Output
Desired Output
You can use continue
if(n == 0) {
sum = 0;
total = 1;
continue;
}
You can initialize the variables inside the while loop
public class AddOrMultiplyNNumbers {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String am;
while (true) {
int sum = 0;
int total = 1;
int n = 0;
System.out.print("enter an integer number: ");
n = input.nextInt();
if(n == 0) {
break;
}
System.out.print("enter either 'a' or 'm': ");
input.nextLine();
am = input.nextLine();
if (am.equals("a")) {
for (int y = 1; y <= n; y++) {
sum = sum + y;
}
System.out.println(sum);
} else if (am.equals("m")) {
for (int x = 1; x <= n; x++) {
total = total * x;
}
System.out.println(total);
}
}
}
}
To zero a variable, simply assign 0 at the appropriate point.
sum = 0;
An appropriate place to insert this statement for your desired output is immediately before the first for loop. Likewise, reset total before the second for.
However, a much better way to write this is to declare the variable where it is needed, as you have done for x and y. This applies to am, sum, total and n
Scanner input = new Scanner(System.in);
while (true) {
System.out.print("enter an integer number: ");
int n = input.nextInt();
if (n == 0) {
break;
}
System.out.print("enter either 'a' or 'm': ");
input.nextLine();
String am = input.nextLine();
if (am.equals("a")) {
int sum = 0;
for (int y = 1; y <= n; y++) {
sum = sum + y;
}
System.out.println(sum);
} else if (am.equals("m")) {
int total = 1;
for (int x = 1; x <= n; x++) {
total = total * x;
}
System.out.println(total);
}
}
I don't know if I fully understand your question, but just do sum=0; and total=1; after you print out the final result. You should also consider doing a try/catch statement for robustness on the nextInt so that characters and strings don't break your program...
try {
n = input.nextInt();
}
catch (Exception e) {
System.out.println("Not a Number");
}

Memory Function Knapsack

Ok, I am having a problem with the Memory Function implementation of the Knapsack problem. My implementation if giving me the incorrect answer in Java but in C++ the same implementation is giving me the correct answer.
import java.io.*;
import java.util.*;
public class KnapsackMF {
public static void main(String args[]){
int wt;
int vl;
long start, end, runTime;
Scanner input = new Scanner(System.in);
int n, W;
System.out.println("Please enter the number of items: ");
n = input.nextInt();
System.out.println("Please enter the capacity of the knapsack: ");
W = input.nextInt();
int[][] V = new int[n+1][W+1];
int[] Wt = new int[n];
int[] Vl = new int[n];
for(int i = 0; i < n; i++){
System.out.println("Enter the weight and the value of item " + i + ": ");
wt = input.nextInt();
vl = input.nextInt();
Wt[i] = wt;
Vl[i] = vl;
}
for(int i = 0; i <= n; i++ ){
for(int j = 0; j <= W; j++){
if(j == 0 || i == 0){
V[i][j] = 0;
}
else{
V[i][j] = -1;
}
}
}
/*
for(int i= 0; i <= n; i++){
for(int j = 0; j <= W; j++){
System.out.print(V[i][j] + " ");
}
System.out.println();
}
*/
start = System.nanoTime();
System.out.println("The highest value is: " + MFKnapsack(n, W, V, Vl, Wt));
end = System.nanoTime();
runTime = (end - start);
System.out.println("Nanoseconds: " + runTime);
for(int i= 0; i <= n; i++){
for(int j = 0; j <= W; j++){
System.out.print(V[i][j] + " ");
}
System.out.println();
}
//system("PAUSE");
}
public static int MFKnapsack(int i, int j, int[][] V, int[] Vl, int[] Wt){
int value = 0;
if(V[i][j] < 0){
if(j < Wt[i-1]){
value = MFKnapsack(i-1, j, V, Vl, Wt);
}
else{
value = Math.max(MFKnapsack(i-1, j, V, Vl, Wt), Vl[i-1] + MFKnapsack(i-1, j-Wt[i-1], V, Vl, Wt));
}
}
V[i][j] = value;
return V[i][j];
}
}
The example I used is out of my book, the inputs should be:
4
5
2 12
1 10
3 20
2 15
The answer to this should be 37 but something is going on that I am not seeing and it is giving me 35.

how to print 2d integer array using scanner in java

System.out.println("Enter the No. of rows to dispaly in 2d");
Scanner n = new Scanner(System.in);
double r = n.nextInt();
System.out.println("Enter the No. of cols to dispaly in 2d");
Scanner v = new Scanner(System.in);
double q= v.nextInt();
System.out.println("Enter the data");
Scanner sc = new Scanner(System.in);
int d = sc.nextInt();
int x[][]={};
int z,y=0;
for ( y=0; y<r.length; y++)
{
for (z=0; z<q.length; z++)
{
x[y][z] = sc.nextInt();
}
}
for ( int m=0; m<x.length; m++)
{ for(int p=0; p<x.length; p++)
{
System.out.println("x[" +m + "][" +p +"]=" +x[m][p]);
}
}
for(int p=0; p<x.length; p++)
is not correct, p need to go from 0 to x[m].length
You need something like this:
for(int m = 0; m < x.length; m++)
{
for(int p = 0; p < x[m].length; p++)
{
System.out.println("x[" + m + "][" + p +"]=" +x[m][p]);
}
}
a 2d array is an array of arrays, so second for loop sees 1d arrays which also have the length property.
Problems with your code:
System.out.println("Enter the No. of rows to dispaly in 2d");
Scanner n = new Scanner(System.in);
double r = n.nextInt();//why use double? use int r=n.nextInt();
System.out.println("Enter the No. of cols to dispaly in 2d");
Scanner v = new Scanner(System.in);//why create another Scanner object, use the old one.
double q= v.nextInt();//int here again
System.out.println("Enter the data");
Scanner sc = new Scanner(System.in);//not another scanner
int d = sc.nextInt();
int x[][]={};
int z,y=0;
for ( y=0; y<r.length; y++)//what's with the length of a double?
{
for (z=0; z<q.length; z++)
{
x[y][z] = sc.nextInt();
}
}
for ( int m=0; m<x.length; m++)
{ for(int p=0; p<x.length; p++)//need to use x[m].length
{
System.out.println("x[" +m + "][" +p +"]=" +x[m][p]);
}
}

Brute Force Algorithm Issue

I've look over the code several time but I keep getting a Array Out of Bound at the line that states:
sum = sum + vectorArray[z]; }
Can anyone see what's wrong?
public class HW1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// The numbers for n are not relevant
System.out.println("Please enter a number for the length of n.");
int n = input.nextInt();
// Creates an array with n values
int[] vectorArray = new int[n];
// Inputs random numbers into the array ranging from -100 to 100.
int dummy;
int temp = 0;
// Loop to generate negative and positive numbers into the array
for (int i = 0; i < n; i++) {
dummy = (int)(Math.random()*2);
if (dummy == 0) {
temp = -1;
} else {
temp = 1; }
vectorArray[i] = ((int)(Math.random()*101)) * temp;
System.out.println(vectorArray[i]); }
int max = -1;
int sum;
for (int x = 0; x < vectorArray.length; x++) {
for (int y = x; x < vectorArray.length; y++) {
sum = 0;
for (int z = x; z <= y; z++) {
sum = sum + vectorArray[z]; }
max = Math.max(max, sum);
} }
System.out.println("The max: " + max);
}
}
change x to y in the for loop
for (int y = x; y < vectorArray.length; y++) {
^
sum = 0;
for (int z = x; z <= y; z++) {
sum = sum + vectorArray[z]; }

Categories

Resources