Java Math.sqrt function rounding down to zero [duplicate] - java

This question already has answers here:
Int division: Why is the result of 1/3 == 0?
(19 answers)
How to divide 1 by 25(1/25) and get result .04 in java [duplicate]
(4 answers)
Closed 1 year ago.
I am trying to write a function to check a T score value and populate half of a 5x5 array.
public void calcTScores()
{
double temp = 0;
double tempSp = 0;
int n = 24;
this.tScores = new String [5][5];
for (int i = 0; i< this.Headers.length; i++){
for (int j = 0; j<this.Headers.length; j++)
{
if(i < j)
{
tempSp += (n-1)*this.SD[i] * this.SD[i] + (n-1)*this.SD[j] * this.SD[j];
tempSp = tempSp/(n+n-2);
tempSp = Math.sqrt(tempSp);
temp = tempSp * Math.sqrt(0.0833);
System.out.println(Math.sqrt(1/12));
temp = ((this.Mean[i] - this.Mean[j])/temp);
if(temp > 2.25 || temp< -2.25)
{
this.tScores[i][j] = "Y";
}
else
{
this.tScores[i][j] = "N";
}
temp = 0;
tempSp = 0;
}
}
}
}
Any idea why Math.sqrt(0.0833) and Math.sqrt(1/12) would evaluate to different values?
The T score when I add the 1/24 and 1/24 value and take the sqrt keeps evaluating to zero but when I plug in the actual decimal it gives me the answer I would expect
Any ideas why this is occuring?

1/12==0 as per integer division

There's nothing wrong with Math.sqrt. You're passing it the number zero.
Math.sqrt(1/12)
1/12 is a division operation on two integers (namely, 1 and 12), so it's going to produce an integer result. 12 goes into 1 zero times, so the integer result is zero. Thus, your expression is
Math.sqrt(0)
Consider
Math.sqrt(1.0/12.0)

Math.sqrt(1/12d)
Cast 1/12 to a double by casting one operand to a double.

Related

My java program only outputs 4's and i don't knwo why [duplicate]

This question already has answers here:
How to make the division of 2 ints produce a float instead of another int?
(9 answers)
Closed 2 years ago.
This code only outputs 4's and I don't know why.
Is it maybe because of the static main or why? thanks
class Calculator {
public static void main(String[] args) {
int x = 3;
boolean op = false;
int pi = 1;
for(int i = 0; i < 99999999; i++) {
if(op == false) {
pi = pi - 1 / x;
op = true;
x = x+2;
System.out.println(pi*4);
} else if(op == true) {
pi = pi + 1 / x;
op = false;
x = x+2;
System.out.println(pi*4);
}
}
}
}
As 1 is of type int, and x also has the type int, 1/x will also be an int. Now, because x>3>2 for the whole program, 1/x is always equal to 0. Therefore, pi will always be 1.
To fix this error, I would suggest changing pi to a double and calculation the inverse of x with 1d/x.
Below line of code always return constant value as you are trying to do 1/x , it's always gives you 0.33,0.11...
And rounding of it will give you 0.
That's why from pi=pi-0, always return constant value.
pi = pi - 1 / x;
op = true;
x = x+2;

Best way to check if a value is an integer? [duplicate]

This question already has answers here:
How to test if a double is an integer
(18 answers)
Closed 8 years ago.
There are several ways to decide if a value is an integer or not.
All of the ways i know are using the divide operation.
Which method is the fastest and:
Is there a method to do this without doing floating point operations?
EDIT: For clarification, my program is only dealing with integer and double values. Here is some of my code:
for (int i = 6;; i++) {
for (int j = i - 1; j > 0; j--) {
double number1 = i;
double number2 = j;
double d = number1 / number2;
int help = (int)d;
if( (d - help) == 0.0){
System.out.println("Whole number found");
}
}
}
Note that int / int will also be an int due to the rules of integral division. You need to promote one of them to floating point or use the idiom 1.0 * a / b if you want to retain a remainder.
If you have a floating point number, f, then
java.lang.Math.floor(f) - f == 0 is probably the best way.
It avoids an intermediate cast to int which can overflow.
This will do what you want!
String str = "1";
try {
Integer.parseInt(str);
} catch (NumberFormatException e) {
System.err.println("Not a number");
}

Project Euler #3 out of integer range java [duplicate]

This question already has answers here:
The literal xyz of type int is out of range
(5 answers)
Closed 8 years ago.
The code is supposed to give back the biggest prime number.
More about the task here: https://projecteuler.net/problem=3
int checkFactors(double na) {
long n = (long) na;
int biggestPrimeFactor = 0;
for (int i = 1; i < n; i++)
if (n % i == 0 && isPrimFaktor(i) && i > biggestPrimeFactor)
biggestPrimeFactor = i;
return biggestPrimeFactor;
}
boolean isPrimeFactor(int n) {
int length= 0;
for (int i = n; i > 0; i--)
if (n % i == 0)
length++;
if (length== 2)
return true;
return false;
}
I decided to make the parameter of checkFactors() a double because I tried to test why my code didn't work properly.
System.out.println(checkFactors(13195));
works and returns "29".
However, System.out.println(checkFactors(600851475143));
does not work,
"600851475143 of type int is out of range".
System.out.println(checkFactors(600851475143.0));
does compile but gives me after a couple of seconds an ArithmeticException.
600851475143 of type int is out of range
This number is bigger than int can store. Appending .0 to the number converts the number into a double which can represent that number
Instead of .0 you can do checkFactors(600851475143d) which ensure the number is a double and not an int
Use long as a data type for na and also biggestPrimeFactor. The values are too large for storing in an int variable.
Try to make Your parameter back to long and make letter L after your large number like this 600851475143L, I think it will work

Calculate median [duplicate]

This question already has answers here:
Why double width = 50/110000; the output is 0.000000000000000?
(3 answers)
Closed 8 years ago.
I can't figure out what is wrong, why doesnt my median work ? Everything works except my median and i have been sitting here for a while and looking at it and still don't understand why it doesnt work.
import java.util.Arrays;
public class Stat{
private int[] värden = new int[100];
public int count = 0; // counter = 0
public int Värden(int värde){
värden[count++]=värde;
return värde;
}
public double medelv(){ //medelvärde
double medelv = 0;
int total = 0;
for(int x = 0; x < count; x++){
total += värden[x];
medelv = (total/count);
}
return medelv;
}
public double medianen(){
Arrays.sort(värden);
double medianen = 0;
for(int x = 0; x < count; x++){
if (värden.length % 2 == 0)
medianen = ((double)värden[värden.length/2] + (double)värden[värden.length/2 - 1])/2;
else
medianen = (double) värden[värden.length/2];
As #zouzou says in the comments, an int divided by another int equals an int. Cast one of them, and it will work.
medelv = ((double)total/count);
A much more concise way to calculate the median:
ArrayList<Integer> integers = new ArrayList<Integer>();
//TO DO: Add the integers to the array list
Collections.sort(integers);
double median;
if (integers.size() > 0) {
int x = integers.size() / 2;
else if (integers.size() % 2 == 0)
median = (integers.get(x - 1) + integers.get(x)) / 2.0;
else median = integers.get(x);
}
I don't see any issues with your logic . Other than finding it in loop . which is not required.
if (värden.length % 2 == 0) {
medianen = ((double)värden[värden.length/2] + (double)värden[värden.length/2 - 1])/2;
} else {
medianen = värden[värden.length/2];
}
If your array length is even then upper portion is double so no issues . If it is not even then you are picking middle ( 5/2 => 2.5 which would become 3 . it is median)
My question is , you declare the array length as 100. Are you filling all the 100 elements ? if not your logic will not work.

Retrieving the first digit of a number [duplicate]

This question already has answers here:
Return first digit of an integer
(25 answers)
Closed 5 years ago.
I am just learning Java and am trying to get my program to retrieve the first digit of a number - for example 543 should return 5, etc. I thought to convert to a string, but I am not sure how I can convert it back? Thanks for any help.
int number = 534;
String numberString = Integer.toString(number);
char firstLetterChar = numberString.charAt(0);
int firstDigit = ????
Almost certainly more efficient than using Strings:
int firstDigit(int x) {
while (x > 9) {
x /= 10;
}
return x;
}
(Works only for nonnegative integers.)
int number = 534;
int firstDigit = Integer.parseInt(Integer.toString(number).substring(0, 1));
firstDigit = number/((int)(pow(10,(int)log(number))));
This should get your first digit using math instead of strings.
In your example log(543) = 2.73 which casted to an int is 2.
pow(10, 2) = 100
543/100 = 5.43 but since it's an int it gets truncated to 5
int firstDigit = Integer.parseInt(Character.toString(firstLetterChar));
int number = 534;
String numberString = "" + number;
char firstLetterchar = numberString.charAt(0);
int firstDigit = Integer.parseInt("" + firstLetterChar);
Integer.parseInt will take a string and return a int.
This example works for any double, not just positive integers and takes into account negative numbers or those less than one. For example, 0.000053 would return 5.
private static int getMostSignificantDigit(double value) {
value = Math.abs(value);
if (value == 0) return 0;
while (value < 1) value *= 10;
char firstChar = String.valueOf(value).charAt(0);
return Integer.parseInt(firstChar + "");
}
To get the first digit, this sticks with String manipulation as it is far easier to read.
int number = 534;
int firstDigit = number/100;
( / ) operator in java divide the numbers without considering the reminder so when we divide 534 by 100 , it gives us (5) .
but if you want to get the last number , you can use (%) operator
int lastDigit = number%10;
which gives us the reminder of the division , so 534%10 , will yield the number 4 .
This way might makes more sense if you don't want to use str methods
int first = 1;
for (int i = 10; i < number; i *= 10) {
first = number / i;
}

Categories