java testing if double is an int - java

Part of my program tests if two numbers are equal. Because certain operations take only doubles and others take only ints, I am comparing ints and doubles. The programs is returning that the two are equal even when they only round to being equal (i.e. 7.5=7). I only want the program to return true if the two actually are equal. I've tried the solutions listed here: How to test if a double is an integer
to determine if my doubles are ints.
All of them appear to work - they compile, but the program still returns 7=7.5
I've tried going the other direction also - converting my ints to doubles - same result. How do I get my program to acknowledge the difference? With the most current suggestion:
import acm.program.ConsoleProgram;
import java.awt.Color;
import acm.io.IODialog;
import java.text.*;
import static java.lang.Math.*;
import java.util.*;
/** Tests to see if user color matches sample colors */
public class ColorMatch extends ConsoleProgram
{
//defining sample colors
Color[] dmc =
{
new Color(255,255,255),
new Color(43,57,41),
new Color(213,39,86),
new Color(0,160,130),
new Color(0,0,0),
};
public void run()
{
average();
}
//averages three colors, then tests for match to given color
public void average()
{
//asks for stitch color
IODialog dialog = new IODialog();
int stitchRed = dialog.readInt("Enter red value: ");
int stitchGreen = dialog.readInt("Enter green value: ");
int stitchBlue = dialog.readInt("Enter blue value: ");
Color stitchColor = new Color(stitchRed,stitchGreen,stitchBlue);
//gets averages for dmc colors
for (Color i:dmc)
{
for (Color j:dmc)
{
for (Color k:dmc)
{
int indexI = Arrays.asList(dmc).indexOf(i);
int indexJ = Arrays.asList(dmc).indexOf(j);
int indexK = Arrays.asList(dmc).indexOf(k);
if (indexI <= indexJ && indexJ <= indexK)
{
int iRed = i.getRed();
int jRed = j.getRed();
int kRed = k.getRed();
int iGreen = i.getGreen();
int jGreen = j.getGreen();
int kGreen = k.getGreen();
int iBlue = i.getBlue();
int jBlue = j.getBlue();
int kBlue = k.getBlue();
double redAverage = (iRed+jRed+kRed)/3;
double greenAverage = (iGreen+jGreen+kGreen)/3;
double blueAverage = (iBlue+jBlue+kBlue)/3;
if (redAverage == (int)redAverage && greenAverage == (int)greenAverage && blueAverage == (int)blueAverage)
{
int rAverage = (int)redAverage;
int gAverage = (int)greenAverage;
int bAverage = (int)blueAverage;
Color colorAverage = new Color(rAverage,gAverage,bAverage);
//tests to see if any average equals the stitch color
if (colorAverage.equals(stitchColor))
{
println("The color match is: " + i + ", " + j + ", " + k);
}
}
}
}
}
}
I plugged in 85s as my test numbers.
The only result should be (0,0,0)+(0,0,0)+(255,255,255), but it is also yielding (43,57,41)+(213,39,86)+(0,160,130) . (41+86+130)/3=85.7!=85.

I think the problem is that you are making a comparison of the 'int' and the 'double' values after casting the double value to int which truncates the decimal part.
For example (7==7.5) is false, but (7==(int)7.5) is true because (int)7.5 = 7.
So if you want strict comparison between an int and a double, you can compare them straight forward without casting. If you want to know more on how casting double to int works, please refer How does double to int cast work in Java.

Related

How to iterate to find the lowest value

Struggling to understand where I went wrong with the iteration at the get best fare method
The array holds [5.77, 2.44, 2.35] and should return the second index, however it seems that it is stuck at the double lowestPrice = lowestPriceRide[0];
I thought that maybe I was putting the return out of scope, but it didn't work.
> import java.lang.*;
import java.util.Arrays;
public class TransitCalculator {
double numberOfDays = 0.0;
double numberOfRides = 0.0;
double pricePerRide = 2.75;
double pricePerWeek = 33.00;
double priceUnlimited = 127.00;
double perRide = 0.00;
public TransitCalculator(double days, double rides){
numberOfDays = days;
numberOfRides = rides;
}
public double unlimited7Price(){
double numOfWeeks = Math.ceil(numberOfDays/7) ; // Math.ceil will return the largest integer that is divisble without a remainder //
double totalPrice = numOfWeeks * pricePerWeek;
return totalPrice / numberOfRides;
}
public double[] getRidePrices(){ // 28/06/2020 Sunday. Math is verified.
double perRide = pricePerRide * numberOfRides / numberOfDays;
double perWeek = unlimited7Price();
double unlimited = priceUnlimited / numberOfRides;
double ridePrices[]; // Declared Array //
ridePrices = new double[] {perRide, perWeek, unlimited}; // New array, with added elements. Could be a mistake since I failed to declare elements//
return ridePrices;
}
public String getBestFare(){ // Error in the iteration and lowest value find! //
double lowestPriceRide[];
lowestPriceRide = getRidePrices();
double lowestPrice = lowestPriceRide[0];
for(int i = 0; i< lowestPriceRide.length; i++) {
if (lowestPrice < lowestPriceRide[i]) {
lowestPriceRide[i] = lowestPrice;
}
}
if(lowestPrice == lowestPriceRide[0]){
System.out.println("You should take the 'Pay per Ride' option in our NYC transit");
}
else if(lowestPrice == lowestPriceRide[1]){
System.out.println("You should take the 'Weekly Unlimited' plan in our NYC Transit");
}
else if(lowestPrice == lowestPriceRide[2]){
System.out.println("You should take the Unlimited ride plan in our NYC Transit");
}
return "at " + lowestPrice + "$ per Ride";
}
public static void main(String[] args){
TransitCalculator test = new TransitCalculator(26, 54);
System.out.println(test.getBestFare()); //
}
}
You are not setting the right value; currently, you set the element in the array to the lowest price instead of setting the lowest price to the element of the array. You also compare against the wrong value; you should check that the current array element is less than the best price, instead of the other way around.
Change
if(lowestPrice < lowestPriceRide[i])
lowestPriceRide[i] = lowestPrice;
To
if(lowestPriceRide[i] < lowestPrice)
lowestPrice = lowestPriceRide[i];
See the updated code in action here.
Note that it is unnecessary to import java.lang, as the package is implicitly imported.
The problem is in your if condition:
if (lowestPrice < lowestPriceRide[i]) {
lowestPriceRide[i] = lowestPrice;
}
You need to see if the current lowestPriceRide[i] is less than the already existing lowestPrice then update your existing lowestPrice. So the condition would be now:
if (lowestPriceRide[i] < lowestPrice) {
lowestPrice = lowestPriceRide[i];
}
This should be your comparison for lowest price :
double lowestPrice = lowestPriceRide[0];
for(int i = 0; i< lowestPriceRide.length; i++) {
if (lowestPriceRide[i] < lowestPrice) {
lowestPrice = lowestPriceRide[i];
}
}

Problem with getting data to go into an array

So for this program, the mean and median are supposed to calculated and displayed but I do not think the data I am inputting is getting put into the array because it runs without error but does not display any data I have put into it.
public static double Mean(double[] gradeArray, int numGrades) {
double totalArray = 0.0;
double mean;
for (int i = 0; i < numGrades; i++) {
totalArray = gradeArray[i] + totalArray;
}
mean = totalArray / numGrades;
return mean;
}
public static double Median(double[] gradeArray, int numGrades) {
double median;
Arrays.sort(gradeArray, 0, numGrades);
if (numGrades % 2 == 0) {
median = ((gradeArray[(numGrades / 2)] + gradeArray[(numGrades / 2 + 1)]) / 2);
} else {
median = gradeArray[(numGrades / 2)];
}
return median;
}
private void Enter_Grades_ButtonActionPerformed(java.awt.event.ActionEvent evt) {
double[] totalArray = new double[25];
String text_box_input_str = null;
double text_box_input_num = 0;
int numGrades = 0;
String num_grades_str;
DecimalFormat df = new DecimalFormat("#0.0##");
do {
try {
text_box_input_str = JOptionPane.showInputDialog(null, "Enter Item Price", "Enter Price", JOptionPane.PLAIN_MESSAGE);
if (text_box_input_str == null || text_box_input_str.isEmpty()) {
return;
}
if (text_box_input_num > 0) {
double[] gradeArray = null;
gradeArray[numGrades] = text_box_input_num;
numGrades++;
num_grades_str = Integer.toString(numGrades);
num_grades_text.setText(num_grades_str);
Mean_Text.setText(df.format(Mean(gradeArray, numGrades)));
Median_Text.setText(df.format(Median(gradeArray, numGrades)));
}
} catch (NumberFormatException e) {
System.out.println("NumberFormatException caught");
JOptionPane.showMessageDialog(null, "You Must Input numeric data!", "Bad Data!", JOptionPane.ERROR_MESSAGE);
}
} while (text_box_input_str != null && !text_box_input_str.isEmpty());
}
I expect the program to calculate the data that is inputted and calculate the mean and median and then display the totals
it looks like text_box_input_num is set to 0, never updated, but then there is an if check if it's > 0
Rather than pointing out the problem with your code directly, I'll give some pointers on how to find it yourself.
break your code down into smaller parts
for each part, write both the method and the tests that prove the method does what you expect
once the individual parts are working, write the method (and tests) that use them.
You'll end up with several methods with names like getValues, hasValue, printError, checkValidValue, showMedian etc. all of which do exactly what you want.
I guarantee that if you do that it'll become pretty clear very quickly what's wrong.

Generate Data Points for Graph from an equation

I don't want to solve an equation and my question is not about Graphs and Trees Data Structures. I am trying to generate Data Points for graph from an equation given by user. I want efficient algorithm, easy to use and easy to maintain data structures. I have two solutions in mind
1: This is trivial and I have seen in many Applications.
String expr = "2*x+3*x";
Evaluator evaluator = new Evaluator();//I have this class
for (int i = start; i < end; i += step)
{
evaluator.setConstant("x", i);
double ans = evaluator.evaluate(expr);
}
This is very slow because each time every step is repeated like tokenzing, verifying, conversion to RPN, preparing stacks and queues and at last result calculation. The possible solution to this problem is somehow caching all stacks and queues but after that a comparison would be required between current expression and previous expression to use last stored state.
2: Currently I am developing second solution. The purpose of this is efficiency and would be used in Symbolic calculation in future.
So far my implementation
Variable.java
import java.text.DecimalFormat;
public class Variable
{
private final double pow;
private final double coefficient;
private final String symbol;
public Variable(String symbol)
{
this.symbol = symbol;
this.pow = 1.0;
this.coefficient = 1.0;
}
public Variable(String symbol, double coefficient, double pow)throws IllegalArgumentException
{
if (coefficient == 0.0)throw new IllegalArgumentException("trying to create variable with coefficient 0");
if (pow == 0.0)throw new IllegalArgumentException("trying to create variable with exponent 0");
this.symbol = symbol;
this.pow = pow;
this.coefficient = coefficient;
}
public final String getSymbol()
{
return this.symbol;
}
public final double getPow()
{
return this.pow;
}
public final double getCoefficient()
{
return this.coefficient;
}
#Override
public String toString()
{
StringBuilder builder = new StringBuilder();
DecimalFormat decimalFormat = new DecimalFormat("#.############");
if (coefficient != 1.0)builder.append(decimalFormat.format(this.coefficient));
builder.append(this.symbol);
if (this.pow != 1.0)builder.append("^").append(decimalFormat.format(this.pow));
return builder.toString();
}
/*
* Stub Method
* Generate some unique hash code
* such that chances of key collision
* become less and easy to identify
* variables with same power and same
* symbol*/
#Override
public int hashCode()
{
return 0;
}
}
Equation.java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
public class Equation
{
private final ArrayList<Boolean> operations;
private final HashMap<String, Variable> variableHashMap;
private int typesOfVariables;
public Equation(Variable variable)
{
this.variableHashMap = new HashMap<>();
this.operations = new ArrayList<>();
this.typesOfVariables = 1;
this.variableHashMap.put(variable.getSymbol(), variable);
}
/*Stub Method*/
public void addVariable(Variable variable, boolean multiply)
{
/*
* Currently not covering many cases
* 1: Add two variables which have same name
* and same pow.
* 2: variable which are wrapped inside functions e.g sin(x)
* and many other.*/
if (multiply && variableHashMap.containsKey(variable.getSymbol()))
{
Variable var = variableHashMap.get(variable.getSymbol());
Variable newVar = new Variable(var.getSymbol(), var.getCoefficient() * variable.getCoefficient(), var.getPow() + variable.getPow());
/*
* Collision chances for variables with same name but
* with different powers*/
this.variableHashMap.replace(var.getSymbol(), newVar);
}
else
{
++this.typesOfVariables;
this.variableHashMap.put(variable.getSymbol(), variable);
}
this.operations.add(multiply);
}
/*Stub Method
*Value for every variable at any point will be different*/
public double solveFor(double x)
{
if (typesOfVariables > 1)throw new IllegalArgumentException("provide values for all variables");
Iterator<HashMap.Entry<String, Variable>> entryIterator = this.variableHashMap.entrySet().iterator();
Variable var;
double ans = 0.0;
if (entryIterator.hasNext())
{
var = entryIterator.next().getValue();
ans = var.getCoefficient() * Math.pow(x, var.getPow());
}
for (int i = 0; entryIterator.hasNext(); i++)
{
var = entryIterator.next().getValue();
if (this.operations.get(i))ans *= var.getCoefficient() * Math.pow(x, var.getPow());
else ans += var.getCoefficient() * Math.pow(x, var.getPow());
}
return ans;
}
#Override
public String toString()
{
StringBuilder builder = new StringBuilder();
Iterator<HashMap.Entry<String, Variable>> entryIterator = this.variableHashMap.entrySet().iterator();
if (entryIterator.hasNext())builder.append(entryIterator.next().getValue().toString());
Variable var;
for (int i = 0; entryIterator.hasNext(); i++)
{
var = entryIterator.next().getValue();
if (this.operations.get(i))builder.append("*").append(var.toString());
else builder.append(var.toString());
}
return builder.toString();
}
}
Main.java
class Main
{
public static void main(String[] args)
{
try
{
long t1 = System.nanoTime();
Variable variable = new Variable("x");
Variable variable1 = new Variable("x", -2.0, 1.0);
Variable variable2 = new Variable("x", 3.0, 4.0);
Equation equation = new Equation(variable);
equation.addVariable(variable1, true);//2x+x
equation.addVariable(variable2, true);
for (int i = 0; i < 1000000; i++)equation.solveFor(i);//Calculate Million Data Points
long t2 = System.nanoTime();
System.out.println((t2-t1)/1000/1000);
System.out.println(equation.toString());
}
catch (Exception e)
{
System.out.println("Error: " + e.getMessage());
}
}
}
Am I going in right direction?
Is there any commonly used Algorithm for this problem?
My main goal is efficiency, code cleanness and code maintainability.
Note: I am not native English speaker so please ignore any grammatical mistake.
Thanks.
I do not see any problem with your first code. Yes may be at every step your code "repeat like tokenzing, verifying, conversion to RPN, preparing stacks and queues and at last result calculation", but in the end all of this is just linear number of steps. So I fail to see how it can make it really slow.
One of the biggest screens I have seen was 2560x1440 pixels, which means that most of the time you would need less than 2500 points to draw your graph there.
If you point is code cleanness and code maintainability, then most probably a code consisting of 5 lines is better than the code consisting of 200.

Convert float to String and String to float in Java

How could I convert from float to string or string to float?
In my case I need to make the assertion between 2 values string (value that I have got from table) and float value that I have calculated.
String valueFromTable = "25";
Float valueCalculated =25.0;
I tried from float to string:
String sSelectivityRate = String.valueOf(valueCalculated);
but the assertion fails
Using Java’s Float class.
float f = Float.parseFloat("25");
String s = Float.toString(25.0f);
To compare it's always better to convert the string to float and compare as two floats. This is because for one float number there are multiple string representations, which are different when compared as strings (e.g. "25" != "25.0" != "25.00" etc.)
Float to string - String.valueOf()
float amount=100.00f;
String strAmount=String.valueOf(amount);
// or Float.toString(float)
String to Float - Float.parseFloat()
String strAmount="100.20";
float amount=Float.parseFloat(strAmount)
// or Float.valueOf(string)
You can try this sample of code:
public class StringToFloat
{
public static void main (String[] args)
{
// String s = "fred"; // do this if you want an exception
String s = "100.00";
try
{
float f = Float.valueOf(s.trim()).floatValue();
System.out.println("float f = " + f);
}
catch (NumberFormatException nfe)
{
System.out.println("NumberFormatException: " + nfe.getMessage());
}
}
}
found here
I believe the following code will help:
float f1 = 1.23f;
String f1Str = Float.toString(f1);
float f2 = Float.parseFloat(f1Str);
This is a possible answer, this will also give the precise data, just need to change the decimal point in the required form.
public class TestStandAlone {
/**
* This method is to main
* #param args void
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
Float f1=152.32f;
BigDecimal roundfinalPrice = new BigDecimal(f1.floatValue()).setScale(2,BigDecimal.ROUND_HALF_UP);
System.out.println("f1 --> "+f1);
String s1=roundfinalPrice.toPlainString();
System.out.println("s1 "+s1);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Output will be
f1 --> 152.32
s1 152.32
If you're looking for, say two decimal places..
Float f = (float)12.34;
String s = new DecimalFormat ("#.00").format (f);
well this method is not a good one, but easy and not suggested. Maybe i should say this is the least effective method and the worse coding practice but, fun to use,
float val=10.0;
String str=val+"";
the empty quotes, add a null string to the variable str, upcasting 'val' to the string type.
There are three ways to convert float to String.
"" + f
Float.toString(f)
String.valueOf(f)
There are two ways Convert String to float
Float.valueOf(str)
Float.parseFloat(str);
Example:-
public class Test {
public static void main(String[] args) {
System.out.println("convert FloatToString " + convertFloatToString(34.0f));
System.out.println("convert FloatToStr Using Float Method " + convertFloatToStrUsingFloatMethod(23.0f));
System.out.println("convert FloatToStr Using String Method " + convertFloatToStrUsingFloatMethod(233.0f));
float f = Float.valueOf("23.00");
}
public static String convertFloatToString(float f) {
return "" + f;
}
public static String convertFloatToStrUsingFloatMethod(float f) {
return Float.toString(f);
}
public static String convertFloatToStrUsingStringMethod(float f) {
return String.valueOf(f);
}
}
String str = "1234.56";
float num = 0.0f;
int digits = str.length()- str.indexOf('.') - 1;
float factor = 1f;
for(int i=0;i<digits;i++) factor /= 10;
for(int i=str.length()-1;i>=0;i--){
if(str.charAt(i) == '.'){
factor = 1;
System.out.println("Reset, value="+num);
continue;
}
num += (str.charAt(i) - '0') * factor;
factor *= 10;
}
System.out.println(num);
To go the full manual route: This method converts doubles to strings by shifting the number's decimal point around and using floor (to long) and modulus to extract the digits. Also, it uses counting by base division to figure out the place where the decimal point belongs. It can also "delete" higher parts of the number once it reaches the places after the decimal point, to avoid losing precision with ultra-large doubles. See commented code at the end. In my testing, it is never less precise than the Java float representations themselves, when they actually show these imprecise lower decimal places.
/**
* Convert the given double to a full string representation, i.e. no scientific notation
* and always twelve digits after the decimal point.
* #param d The double to be converted
* #return A full string representation
*/
public static String fullDoubleToString(final double d) {
// treat 0 separately, it will cause problems on the below algorithm
if (d == 0) {
return "0.000000000000";
}
// find the number of digits above the decimal point
double testD = Math.abs(d);
int digitsBeforePoint = 0;
while (testD >= 1) {
// doesn't matter that this loses precision on the lower end
testD /= 10d;
++digitsBeforePoint;
}
// create the decimal digits
StringBuilder repr = new StringBuilder();
// 10^ exponent to determine divisor and current decimal place
int digitIndex = digitsBeforePoint;
double dabs = Math.abs(d);
while (digitIndex > 0) {
// Recieves digit at current power of ten (= place in decimal number)
long digit = (long)Math.floor(dabs / Math.pow(10, digitIndex-1)) % 10;
repr.append(digit);
--digitIndex;
}
// insert decimal point
if (digitIndex == 0) {
repr.append(".");
}
// remove any parts above the decimal point, they create accuracy problems
long digit = 0;
dabs -= (long)Math.floor(dabs);
// Because of inaccuracy, move to entirely new system of computing digits after decimal place.
while (digitIndex > -12) {
// Shift decimal point one step to the right
dabs *= 10d;
final var oldDigit = digit;
digit = (long)Math.floor(dabs) % 10;
repr.append(digit);
// This may avoid float inaccuracy at the very last decimal places.
// However, in practice, inaccuracy is still as high as even Java itself reports.
// dabs -= oldDigit * 10l;
--digitIndex;
}
return repr.insert(0, d < 0 ? "-" : "").toString();
}
Note that while StringBuilder is used for speed, this method can easily be rewritten to use arrays and therefore also work in other languages.

Format double to at least one significant digit in Java/Android

I have a DecimalFormat object which I'm using to format all of my double values to a set number of digits (let's say 2) when I'm displaying them. I would like it to normally format to 2 decimal places, but I always want at least one significant digit. For example, if my value is 0.2 then my formatter spits out 0.20 and that's great. However, if my value is 0.000034 my formatter will spit out 0.00 and I would prefer my formatter spit out 0.00003.
The number formatters in Objective-C do this very simply, I can just set a max number of digits I want to show at 2 and the minimum number of significant digits at 1 and it produces my desired output, but how can I do it in Java?
I appreciate any help anyone can offer me.
Kyle
Edit: I'm interested in rounding the values so 0.000037 displays as 0.00004.
It's not efficient, so if you perform this operation often I'd try another solution, but if you only call it occasionally this method will work.
import java.text.DecimalFormat;
public class Rounder {
public static void main(String[] args) {
double value = 0.0000037d;
// size to the maximum number of digits you'd like to show
// used to avoid representing the number using scientific notation
// when converting to string
DecimalFormat maxDigitsFormatter = new DecimalFormat("#.###################");
StringBuilder pattern = new StringBuilder().append("0.00");
if(value < 0.01d){
String s = maxDigitsFormatter.format(value);
int i = s.indexOf(".") + 3;
while(i < s.length()-1){
pattern.append("0");
i++;
}
}
DecimalFormat df = new DecimalFormat(pattern.toString());
System.out.println("value = " + value);
System.out.println("formatted value = " + maxDigitsFormatter.format(value));
System.out.println("pattern = " + pattern);
System.out.println("rounded = " + df.format(value));
}
}
import java.math.BigDecimal;
import java.math.MathContext;
public class Test {
public static void main(String[] args) {
String input = 0.000034+"";
//String input = 0.20+"";
int max = 2;
int min =1;
System.out.println(getRes(input,max,min));
}
private static String getRes(String input,int max,int min) {
double x = Double.parseDouble(((new BigDecimal(input)).unscaledValue().intValue()+"").substring(0,min));
int n = (new BigDecimal(input)).scale();
String res = new BigDecimal(x/Math.pow(10,n)).round(MathContext.DECIMAL64).setScale(n).toString();
if(n<max){
for(int i=0;i<max;i++){
res+="0";
}
}
return res;
}
}

Categories

Resources