Minkowski distance code - java

I have the java code below which i used to calculate the Minkowski distance,
class Minkowski {
public static void main( String [] arg){
int p=2;
double [] Mski = new double[5];
double [] a = { 1, 2, 3, 4,5};
double [] b = { 6,7,8,9,11};
System.out.println(Arrays.toString(Minkowski1(a,b,p);
}
public static double Minkowski1( double [] a , double [] b, int q)
{
double sum = 0;
for(int f = 0; f < a.length; f++){
sum += Math.pow( Math.abs(a[f] - b[f]),q );
}
return Math.pow(sum, 1.0 / q);
}
The Code produce different result from a Minkowski distance matlab code :
for i=1 : 5
result2(i)=sum(abs(X(i)-Y(i)).^p).^(1/p)
end
the result in matlab is 5 5 5 5 6,and java one is not same
any suggestion please

Your problem is, that
1/q=0
in java (at least for q>1) but
1/p!=0
in matlab.
So you need to replace the integer division through floating point division and use
1.0/q

Related

Java power of number calculation problem with big numbers [duplicate]

This question already has an answer here:
Why in one case multiplying big numbers gives a wrong result?
(1 answer)
Closed 2 years ago.
I am new to Java and when I was trying to find power of number without Math.pow method I realized the answer was not right. And I want to learn why?
public class Main() {
int x = 1919;
int y = x*x*x*x;
public static void main(String[] args) {
System.out.println(y);
}
}
Output: 2043765249
But normally answer is: 13561255518721
If you go step by step, you'll see that at a moment the value becomes negative, that's because you reach Integer.MAX_VALUE which is 2^31 -1
int x = 1919;
int y = 1;
for (int i = 0; i < 4; i++) {
y *= x;
System.out.println(i + "> " + y);
}
0> 1919
1> 3682561
2> -1523100033
3> 2043765249
You may use a bigger type like double or BigInteger
double x = 1919;
double y = x * x * x * x;
System.out.println(y); // 1.3561255518721E13
BigInteger b = BigInteger.valueOf(1919).pow(4);
System.out.println(b); // 13561255518721
You're using an int for the answer, you're getting a numeric overflow.
Use double or long or BigInteger for y and you'll get the right answer.
public class Main {
public static void main(String[] args) {
System.out.println(Math.pow(1919, 4));
System.out.println((double) 1919*1919*1919*1919);
}
}
Outputs the same value.
Use long instead of int
public class Main{
public static void main(String[] args) {
long x = 1919;
long y = x*x*x*x;
System.out.println(y);
}
}
Read about variables in Java.

sum of the digits of the number 2^1000 in java [duplicate]

This question already has answers here:
Sum of the digits of the number 2^1000 [closed]
(11 answers)
Closed 3 years ago.
import java.math.*;
public class PowerDigitSum {
public static void main(String[] args) {
double[] digits ;
digits = new double[302];
double i = Math.pow(2, 1000);
double c = 301;
double c1 = 0;
double d = 0;
while(c>=0) {
c1 = Math.pow(10, c);
d = Math.floor(i/c1);
i = i - d*c1;
digits[(int)c] = (int)d;
c = c-1;
}
double sum = 0;
c = 0;
while (c<302) {
sum = sum+digits[(int)c];
c= c+1;
}
System.out.println(sum);
}
}
The output is 1281 but that's not correct according to projecteuler. What am I doing wrong?
You can't do correct math with double values that large due to their limited nature.
You could probably fix your code with BigDecimal, but it is much easier using BigInteger. Hint: it has a pow method, and you can work out the digit sum starting from toString.

A program that finds the average of a number of integers

I have integers a, b, c, d. I want to design a program which will output me the average of the numbers after discarding the highest and the lowest numbers. So if I have input 3 7 5 3, I would want output 4. I have to do this without using the math library, loops or arrays. My code is below. It runs but gives the wrong output. What am I doing wrong?
public class average{
public static void main(String[] args) {
int a, b, c, d;
a = Integer.valueOf(args[0]);
b = Integer.valueOf(args[1]);
c = Integer.valueOf(args[2]);
d = Integer.valueOf(args[3]);
if ((a>b)&&(a>c)&&(a>d))
{a= 0;
}
if ((a<b)&&(a<c)&&(a<d))
{a= 0;
}
if ((b>a)&&(b>c)&&(b>d))
{b=0;
}
if ((b<a)&&(b<c)&&(b<d))
{b=0;
}
if ((c>a)&&(c>b)&&(c>d))
{c=0;
}
if ((c<a)&&(c<b)&&(c<d))
{c=0;
}
if ((d>a)&&(d>b)&&(d>c))
{d=0;
}
if ((d<a)&&(d<b)&&(d<c))
{d=0;
}
int x;
// x is the average of all the numbers excluding the largest and the smallest
x= ((a+b+c+d)/2);
System.out.println(x);
}
}
in your input example 3 3 5 7, a and b are equal. but your code only compares for less than (<) value, so when your code execution reaches line “x= ((a+b+c+d)/2);” you have a=3, b=3 and c=5 which results into x =5.
Hope this explains why you are not getting expected result.
The if conditions you provided do not work as expected when two or more numbers are same, which is explained clearly by Rai.
You can store the minimum and maximum values in min and max variables.
int min = a, max = a;
if(b > max)
{
max = b;
}
if(c > max)
{
max = c;
}
if(d > max)
{
max = d;
}
Similarly for min.
And when you are summing the numbers for average, just add all four numbers and subtract the sum of min and max.
I hope it is clear enough.
A quick and short solution where there is no loop, no arrays and math library is not used:
public static void main(String[] args) {
args = new String[] {"3", "7", "5", "3"};
int a = Integer.valueOf(args[0]);
int b = Integer.valueOf(args[1]);
int c = Integer.valueOf(args[2]);
int d = Integer.valueOf(args[3]);
List<Integer> numbers = new ArrayList<>();
numbers.add(a);
numbers.add(b);
numbers.add(c);
numbers.add(d);
Integer min = numbers.stream().min(Integer::compare).get();
Integer max = numbers.stream().max(Integer::compare).get();
numbers.remove(min);
numbers.remove(max);
int average = (numbers.get(0) + numbers.get(1)) / 2;
System.out.println("average: " + average);
}

Calculate e^x without inbuilt functions in Java

I am a beginner in Java and currently going through the "how to think like a computer scientist" beginners book. I am stuck with a problem in the iteration chapter. Could anyone please point me in the right direction?
When I use math.exp, I get an answer that is completely different from the answer my code obtains.
Note, it's not homework.
Here's the question:
One way to calculate ex is to use the infinite series expansion
ex = 1 + x + x2 /2! + x3/3! + x4/4! +...
If the loop variable is named i, then the ith term is xi/i!.
Write a method called myexp that adds up the first n terms of this
series.
So here's the code:
public class InfiniteExpansion {
public static void main(String[] args){
Scanner infinite = new Scanner(System.in);
System.out.println("what is the value of X?");
double x = infinite.nextDouble();
System.out.println("what is the power?");
int power = infinite.nextInt();
System.out.println(Math.exp(power));//for comparison
System.out.println("the final value of series is: "+myExp(x, power));
}
public static double myExp(double myX, double myPower){
double firstResult = myX;
double denom = 1;
double sum =myX;
for(int count =1;count<myPower;count++){
firstResult = firstResult*myX;//handles the numerator
denom = denom*(denom+1);//handles the denominator
firstResult = firstResult/denom;//handles the segment
sum =sum+firstResult;// adds up the different segments
}
return (sum+1);//gets the final result
}
}
The assignment denom = denom*(denom+1) is going to give a sequence as follows: 1, 1*2=2, 2*3=6, 6*7=42, 42*43=...
But you want denom = denom*count.
Let's say in general we just want to print the first n factorials starting with 1!: 1!, 2!, 3!, ..., n!. At the kth term, we take the k-1th term and multiply by k. That would be computing k! recursively on the previous term. Concrete examples: 4! is 3! times 4, 6! is 5! times 6.
In code, we have
var n = 7;
var a = 1;
for (int i = 1; i <= n; i++ ) {
a = a*i; // Here's the recursion mentioned above.
System.out.println(i+'! is '+a);
}
Try running the above and compare to see what you get with running the following:
var n = 7;
var a = 1;
for (int i = 1; i <= n; i++ ) {
a = a*(a+1);
System.out.println('Is '+i+'! equal to '+a+'?');
}
There are several errors here:
firstResult should start from 1, so that it goes 1+x+x^2 instead of 1+x^2+x^3
As timctran stated you are not calculating the factorial in a correct way.
To wrap up you can simplify your operations to:
firstResult = firstResult * myX / (count+1);
sum += firstResult;
Edit:
- I ran the code and saw that Math.exp(power) is printed instead of Math.exp(x)
- My first item is wrong since sum is initialized to myX.
Why make it complicated? I tried a solution and it looks like this:
//One way to calculate ex is to use the infinite series expansion
//ex = 1 + x + x2 /2! + x3/3! + x4/4! +...
//If the loop variable is named i, then the ith term is xi/i!.
//
//Write a method called myexp that adds up the first n terms of this series.
import java.util.Scanner;
public class InfiniteExpansion2 {
public static void main(String[] args) {
Scanner infinite = new Scanner(System.in);
System.out.println("what is the value of X?");
double x = infinite.nextDouble();
System.out.println("what is the value of I?"); // !
int power = infinite.nextInt();
System.out.println(Math.exp(power));//for comparison
System.out.println("the final value of series is: " + myCalc(x, power));
}
public static double fac(double myI) {
if (myI > 1) {
return myI * fac(myI - 1);
} else {
return 1;
}
}
public static double exp(double myX, double myE) {
double result;
if (myE == 0) {
result = 1;
} else {
result = myX;
}
for (int i = 1; i < myE; i++) {
result *= myX;
}
return result;
}
public static double myCalc(double myX, double myI) {
double sum = 0;
for (int i = 0; i <= myI; i++) { // x^0 is 1
sum += (exp(myX, i) / fac(i));
}
return sum;
}
}
If you want to think like an engineer, I'd do it like this:
keep it simple
break it into pieces
stick closely to the task (like I named the var myI, not myPower - seems clearer to me, for a start - that way you won't get confused)
I hope you like it!
I tried a solution and it looks like this:
public class Fact {
public int facto(int n){
if(n==0)
return 1;
else
return n*facto(n-1);
}
}
}
import java.util.Scanner;
public class Ex {
public static void main(String[] args){
Fact myexp=new Fact();
Scanner input=new Scanner(System.in);
int n=1;
double e=1,i=0,x;
int j=1;
System.out.println("Enter n: ");
n=input.nextInt();
System.out.println("Enter x: ");
x=input.nextDouble();
while(j<=n)
{
int a=myexp.facto(j);
double y=Math.pow(x,j)/(double)a;
i=i+y;
++j;
}
e=e+i;
System.out.println("e^x= "+ e);
}
}

Does Java have an exponential operator?

Is there an exponential operator in Java?
For example, if a user is prompted to enter two numbers and they enter 3 and 2, the correct answer would be 9.
import java.util.Scanner;
public class Exponentiation {
public static double powerOf (double p) {
double pCubed;
pCubed = p*p;
return (pCubed);
}
public static void main (String [] args) {
Scanner in = new Scanner (System.in);
double num = 2.0;
double cube;
System.out.print ("Please put two numbers: ");
num = in.nextInt();
cube = powerOf(num);
System.out.println (cube);
}
}
There is no operator, but there is a method.
Math.pow(2, 3) // 8.0
Math.pow(3, 2) // 9.0
FYI, a common mistake is to assume 2 ^ 3 is 2 to the 3rd power. It is not. The caret is a valid operator in Java (and similar languages), but it is binary xor.
To do this with user input:
public static void getPow(){
Scanner sc = new Scanner(System.in);
System.out.println("Enter first integer: "); // 3
int first = sc.nextInt();
System.out.println("Enter second integer: "); // 2
int second = sc.nextInt();
System.out.println(first + " to the power of " + second + " is " +
(int) Math.pow(first, second)); // outputs 9
The easiest way is to use Math library.
Use Math.pow(a, b) and the result will be a^b
If you want to do it yourself, you have to use for-loop
// Works only for b >= 1
public static double myPow(double a, int b){
double res =1;
for (int i = 0; i < b; i++) {
res *= a;
}
return res;
}
Using:
double base = 2;
int exp = 3;
double whatIWantToKnow = myPow(2, 3);
There is the Math.pow(double a, double b) method. Note that it returns a double, you will have to cast it to an int like (int)Math.pow(double a, double b).
you can use the pow method from the Math class. The following code will output 2 raised to 3 (8)
System.out.println(Math.pow(2, 3));
In case if anyone wants to create there own exponential function using recursion, below is for your reference.
public static double power(double value, double p) {
if (p <= 0)
return 1;
return value * power(value, p - 1);
}

Categories