Stop a number at a certain range - java

Basic problem but I can't seem to wrap my head around it:
I have something that rotates and I want to stop it at a certain range.
So I want it to return false if the rotation (which is in double) is within a certain range.
Example
Rotation = 182, StopAt 180, Accuracy 2. So should stop.
Rotation = 182, StopAt 180, Accuracy 1. So should not stop.
Current I have:
/**
*
* #return
* number = 100, current = 105, accuracy = 10
* Example
* 105c / 100n = 1.05..
* 10c / 100n = 0.1..
*/
public boolean stopAtRange(double number, double current, double accuracy)
{
if(current / number) + accuracy)
{
return true;
}
return false;
}

In Java if only takes boolean values, and integer values aren't converted to boolean.
To achieve what you want, your method should be like this
public boolean stopAtRange(double number, double current, double accuracy)
{
if( Math.abs(current - number) <= accuracy)
{
return true;
}
return false;
}
This work both if current is bigger or smaller than number. If you only want to stop if current is bigger or at least equals to number, than you should remove the Math.abs
I also suggest to use this version:
public static boolean stopAtRange(double number, double current, double accuracy) {
return Math.abs(current - number) <= accuracy;
}
because it's more compact, and is optimized, for performances as well.

Your question is a bit confusing, but I'll try my best to help. :)
This code won't compile:
if(current / number) + accuracy)
Firstly, you've opened one bracket and then closed two. You would want:
if((current / number) + accuracy)
Secondly, this won't evaluate to a Boolean value (true or false), which is necessary for your if statement to work. You want:
public boolean stopAtRange(double number, double current, double accuracy)
{
if(Math.abs(current - number) <= accuracy) return true;
return false;
}
This works out the difference between your numbers (100 & 105) and confirms if they are within the range (10).
Hope this helps!

Following will stop if current is +/-accuracy away from number:
public boolean stopAtRange(double number, double current, double accuracy)
{
if( Math.abs(current - number) <= accuracy)
{
return true;
}
return false;
}

if accepts a boolean value, not a double. Something like:
public boolean stopAtRange(double number, double current, double accuracy)
{
if(Math.abs(current-number) <= accuracy)
{
return true;
}
return false;
}

Related

How to prevent a recursive method from changing a value of a variable?

I'm learning Java, and I'm stuck on a recursion problem.
I need to use a recursive method to check if a number is an Armstrong number or not.
My code:
public class ArmstrongChecker {
public boolean isArmstrong(int number) {
// check if the number is a negative number
if (number < 0) {
return false;
}
ArmstrongChecker armstrongChecker = new ArmstrongChecker();
// find the length of the number
int length = armstrongChecker.lengthChecker(number);
// create a variable to store the sum of the digits of the number
int sum = 0;
// find the individual digits and raise to the power of the numbers of digits
if (number != 0) {
int digit = Math.floorMod(number, 10);
int powerRaised = (int) Math.pow(digit, length);
sum = sum + powerRaised;
isArmstrong(number / 10);
}
return sum == number;
}
// method to check the length of the number
public int lengthChecker(int number) {
int length = String.valueOf(number).length();
return length;
}
}
How do I prevent int length in isArmstrong() method from changing its value.
While you are not changing it's value in the posted code, you could mark that variable to be a constant. This way the compiler can error out if you tried to assign a new value.
final int length = armstrongChecker.lengthChecker(number);
As I've already said in the comments, your solution has the following issues:
The result of the recursive call isArmstrong() is being ignored;
There's no need for spawning new instances of ArmstrongChecker. And this method doesn't require object creation at all, it can be implemented as static.
Checking if the number is an Armstrong number boils down to calculating its Armstrong sum, the solution will be cleaner if you implement only this part using recursion.
It might look like this:
public static boolean isArmstrong(int number) {
if (number < 0) return false;
if (number < 10) return true;
return number == getArmstrongSum(number, String.valueOf(number).length());
}
public static int getArmstrongSum(int number, int power) {
if (number == 0) {
return 0;
}
return (int) Math.pow(number % 10, power) + getArmstrongSum(number / 10, power);
}
main()
public static void main(String[] args) {
System.out.println(isArmstrong(370)); // true
System.out.println(isArmstrong(12)); // false
System.out.println(isArmstrong(54)); // false
System.out.println(isArmstrong(153)); // true
}
Output:
true
false
false
true
You need to get the length once for whole recursion, so the cleanest approach would be to pass down both the number and the length into the recursion. An easy way to do this is to have one method that is the public face of the API, and another that does the recursion.
public class ArmstrongChecker {
public boolean isArmstrong(int number) {
if (number < 0) {
return false;
}
int length = lengthChecker(number);
int sum = armstrongSum(number, length);
return sum == number;
}
private int armstrongSum(int number, int length) {
int sum = 0;
if (number != 0) {
int digit = Math.floorMod(number, 10);
int powerRaised = (int) Math.pow(digit, length);
sum += powerRaised;
sum += armstrongSum(number / 10, length);
}
return sum;
}
public int lengthChecker(int number) {
int length = String.valueOf(number).length();
return length;
}
}
This is pretty common in recursion, where the parameters to the recursive part of the algorithm are a little different (usually there are more of them) than what you want a client of the API to have to pass in. The number changes in each recursive call, where number / 10 is passed down, but the same length is passed all the way through.
Notice that the recursive armstrongSum uses the return value from the recursive call, and that there is no need to create another instance of ArmstrongChecker when you are already in an instance method of the class.

Check If a number is contained in an interval without using "if" or loops

So, I have a basic question. I could solve this easily but I am dumbfounded at the moment because my teacher would like us to solve this not using any if statements or loops. So the interval is not an array. A basic example is [1,6] or (1,6) or a mixed of both open and closed. So, 5 would be in the interval. I need a contains(double number) method that checks if the number is inside. How can you possibly do this without an if or loop? Am I stupid? Is there some magic method that I have not stumbled upon that does this?
My approach would be something along the lines of
public double contains(number)
{
if (number >= leftEndPoint && number <= rightEndPoint) //lets assume interval is "closed" heh. on both ends
return true;
return false;
}
But...We can't use an if statement or loop.
Note that the expression in the condition of an if statement evaluates to either true or false. This means you can return the value directly rather than having an explicit if. In general,
if (x)
return true;
else
return false;
can be replaced by
return x;
You want to return a boolean value of true or false. Every conditional expression returns such a value, which you can return in your function without having if-statements:
public boolean contains(double number) {
return number >= startNum && number <= endNum;
}
That works perfectly fine if you - of course - define the startNum and endNum somewhere.
if(x)
return true;
never makes sense. At least, it never makes more sense than if (true) /* something */; or if (isOn == true) /**/.
Please write:
return number >= leftEndPoint && number <= rightEndPoint;
and thank you.
Here is my solution. Pretty verbose, but should be maintainable.
public class Interval {
final int bottom;
final int top;
final IntervalEvaluationStrategy strategy;
public Interval(final int bottom, final int top, final IntervalEvaluationStrategy strategy) {
this.bottom = bottom;
this.top = top;
this.strategy = strategy;
}
public boolean check(int value) {
return strategy.evaluate(value, bottom, top);
}
public enum IntervalEvaluationStrategy {
OPEN {
#Override
boolean evaluate(int value, int bottom, int top) {
return CLOSED.evaluate(value, bottom, top)
|| value == bottom
|| value == top;
}
},
CLOSED {
#Override
boolean evaluate(int value, int bottom, int top) {
return value > bottom
&& value < top;
}
};
abstract boolean evaluate(int value, int bottom, int top);
}
public static void main(String[] args) {
assert checkInterval(5, 5, 10, IntervalEvaluationStrategy.OPEN);
}
//helper method with example usage
public static boolean checkInterval(final int value, final int bottom, final int top, IntervalEvaluationStrategy strategy) {
final Interval interval = new Interval(bottom, top, strategy);
return interval.check(value);
}
}
Conditional operator can also be used.
For example:
return (number >= leftEndPoint && number <= rightEndPoint)?true:false;

Correct implementation of the equals()-Method for fractions

I want that the printn methods give me "Asterix" and "Oberlix" since 3/4 is the same as 6/8.
HashMap hm = new HashMap();
hm.put(new Fraction(3, 4), "Asterix");
hm.put(new Fraction(19, 12), "Oberlix");
System.out.println(hm.get(new Fraction(6, 8)));
System.out.println(hm.get(new Fraction(38, 24)));
So that is how I implemented the equals-Method:
public boolean equals(Object obj) {
boolean isEqual = false;
if(obj instanceof Fraction) {
Fraction frac = (Fraction) obj;
if(((double) this.numerator / (double) this.denumerator) == ((double) frac.numerator / (double) frac.denumerator)) {
isEqual = true;
}
}
return isEqual;
}
Obviously I did something wrong, because that doesn't work and my print method returns "null". My idea was that if I devide the numerator and the denumerator of both fractions, the result must be equal, if the fractions are equal (3/4 is the same as 6/8).
Sorry guys, I guess the mistake must be somehow obvious but I can't find it.
You could do for equals
return denominator * other.numerator == numerator * other.denominator;
But nicer is to make canonical Fraction.
Either in the equals or in the constructor normalize the fraction: 6/8 becoming 3/4.
public class Fraction implements Number {
private final int numerator;
private final int denominator;
public Fraction(int numerator, int denominator) {
if (denominator < 0) {
denominator = -denominator;
numberator = -numerator;
}
int commonFactor = gcd(numerator, denominator);
this.numerator = numerator / commonFactor;
this.denominator = denominator / commonFactor;
}
#Override
public boolean equals(Object other) {
...
Fraction otherFraction = ...
return denominator == otherFraction.denominator
&& numerator == otherFraction.numerator;
}
private static int gcd(int x, int y) {
x = Math.abs(x);
y = Math.abs(y);
...
while (x != y) {
if (x > y) {
x -= y;
} else {
y -= x;
}
}
return x;
}
What is nicer? You can now make a hashCode:
#Override
int hashCode() {
return denominator * 31 + numerator;
}
Floating point is an approximating sum of a limited number of powers of 2.
For a HashMap to work, you need to implement both equals and hashCode. I'll provide a partial answer, for equals only, because I don't have much time.
To compare two fractions without resorting to doubles, just do some simple arithmetic. You have two fractions, a/b and c/d. Assuming the denominators are nonzero:
a/b == c/d
(multiply left and right by b)
a == c/d*b
(multiply left and right by d)
a*d == c*b
So:
public boolean equals(Object obj) {
if (!(obj instanceof Fraction)) {
return false;
}
Fraction other = (Fraction) obj;
return this.numerator * other.denominator == other.numerator * this.denominator;
}
Note that this won't work for very large fractions; they will overflow. Cast to long if you want to deal with these correctly.
For implementing hashCode, you could simplify the fraction using the Euclidean algorithm, then xor the hash codes of the numerator and the denominator.
You should never compare double with == because System.out.println(0.1+0.1+0.1) will not always be 0.3 (for me, it output 0.30000000000000004). Use equals or compare method from Double.
Because you are storing both numerator and denumenator in your class Fraction, you should use a close enough condition with a custom epsilon in your equals method:
public boolean equals(Object obj) {
boolean isEqual = false;
if(obj instanceof Fraction) {
Fraction frac = (Fraction) obj;
if(Math.abs(((double)this.numerator)/this.denumerator) - ((double)frac.numerator)/frac.denumerator) < .00000001/*epsilon*/) {
isEqual = true;
}
}
return isEqual;
}
Also, you will need to override the hashCode method in your class Fraction in order to use HashMap. Since this equals implementation only depend on one value (the result of the fraction) you could use the following :
public int hashCode()
{
return 0;//all Fraction return the same hashCode, which make HashMap call equals each time
//EDIT: the following is WRONG: assuming eps = 0.1, 299/100 is equals to 300/100 but hashCode will be different (2 and 3).
//return this.numerator/this.denumerator ;//since those are int (I guess),
//it will truncate the floating part. So you will just check for the integer part.
}
as the posts from above, the way to your solution is the use of "hasCode()" and not equals().
Here is an option on how you can get the proper hashCode:
#Override
public int hashCode() {
// Calculating with double is troublesome sometimes, so i use BigDecimal here
BigDecimal value = BigDecimal.valueOf(this.numerator).divide(BigDecimal.valueOf(this.denumerator), RoundingMode.HALF_UP);
// after this, i just return the hashCode i would get, if if my parameter was a simple Double Value:
return Double.valueOf(value.doubleValue()).hashCode();
}
hope this helps!

How to compute `ulp`when `Math.ulp` is missing?

I need the ulp for a given double value, but since I am developing for Codename ONE, ulp(double) is not provided. Does anyone know an efficient algorithm to compute ulp in Java? Codename ONE provides just some of the methods in the Math class (javadoc for the CN1 version) and some of the gaps are filled in MathUtil.
As a workaround, I use this (incorrect) code until I find a working replacement:
private double ulp(double y) {
return y/1e15;
}
EDIT: I "rolled my own" and have just posted my code for review. Just in case someone else needs this.
Ok, since I didn't find a working replacement (both Apache Harmony and OpenJDK end up using native methods that are not available on CN1), I wrote my own version (results tested against OpenJDK-version). Just in case anyone needs it.
As for codename One: I submitted a patch to the MathUtil class, so hopefully this will be added sooner or later.
/*
* use a precalculated value for the ulp of Double.MAX_VALUE
*/
private static final double MAX_ULP = 1.9958403095347198E292;
/**
* Returns the size of an ulp (units in the last place) of the argument.
* #param d value whose ulp is to be returned
* #return size of an ulp for the argument
*/
#Override
public double ulp(double d) {
if (Double.isNaN(d)) {
// If the argument is NaN, then the result is NaN.
return Double.NaN;
}
if (Double.isInfinite(d)) {
// If the argument is positive or negative infinity, then the
// result is positive infinity.
return Double.POSITIVE_INFINITY;
}
if (d == 0.0) {
// If the argument is positive or negative zero, then the result is Double.MIN_VALUE.
return Double.MIN_VALUE;
}
d = Math.abs(d);
if (d == Double.MAX_VALUE) {
// If the argument is Double.MAX_VALUE, then the result is equal to 2^971.
return MAX_ULP;
}
return nextAfter(d, Double.MAX_VALUE) - d;
}
#Override
public double copySign(double x, double y) {
return com.codename1.util.MathUtil.copysign(x,y);
}
private boolean isSameSign(double x, double y) {
return copySign(x, y) == x;
}
/**
* Returns the next representable floating point number after the first
* argument in the direction of the second argument.
*
* #param start starting value
* #param direction value indicating which of the neighboring representable
* floating point number to return
* #return The floating-point number next to {#code start} in the
* direction of {#direction}.
*/
#Override
public double nextAfter(final double start, final double direction) {
if (Double.isNaN(start) || Double.isNaN(direction)) {
// If either argument is a NaN, then NaN is returned.
return Double.NaN;
}
if (start == direction) {
// If both arguments compare as equal the second argument is returned.
return direction;
}
final double absStart = Math.abs(start);
final double absDir = Math.abs(direction);
final boolean toZero = !isSameSign(start, direction) || absDir < absStart;
if (toZero) {
// we are reducing the magnitude, going toward zero.
if (absStart == Double.MIN_VALUE) {
return copySign(0.0, start);
}
if (Double.isInfinite(absStart)) {
return copySign(Double.MAX_VALUE, start);
}
return copySign(Double.longBitsToDouble(Double.doubleToLongBits(absStart) - 1L), start);
} else {
// we are increasing the magnitude, toward +-Infinity
if (start == 0.0) {
return copySign(Double.MIN_VALUE, direction);
}
if (absStart == Double.MAX_VALUE) {
return copySign(Double.POSITIVE_INFINITY, start);
}
return copySign(Double.longBitsToDouble(Double.doubleToLongBits(absStart) + 1L), start);
}
}
I'm not sure why your implementation of ULP takes signs and other criteria into account, when ULP returns the absolute value of the difference between the given value and the next floating point number in magnitude.
Here's an example of all you need to do; it's written in C#, but it's close enough to Java to understand.
public static double ULP(double value)
{
// This is actually a constant in the same static class as this method, but
// we put it here for brevity of this example.
const double MaxULP = 1.9958403095347198116563727130368E+292;
if (Double.IsNaN(value))
{
return Double.NaN;
}
else if (Double.IsPositiveInfinity(value) || Double.IsNegativeInfinity(value))
{
return Double.PositiveInfinity;
}
else if (value == 0.0)
{
return Double.Epsilon; // Equivalent of Double.MIN_VALUE in Java; Double.MinValue in C# is the actual minimum value a double can hold.
}
else if (Math.Abs(value) == Double.MaxValue)
{
return MaxULP;
}
// All you need to understand about DoubleInfo is that it's a helper struct
// that provides more functionality than is used here, but in this situation,
// we only use the `Bits` property, which is just the double converted into a
// long.
DoubleInfo info = new DoubleInfo(value);
// This is safe because we already checked for value == Double.MaxValue.
return Math.Abs(BitConverter.Int64BitsToDouble(info.Bits + 1) - value);
}

How to write a function that can calculate power in Java. No loops

I've been trying to write a simple function in Java that can calculate a number to the nth power without using loops.
I then found the Math.pow(a, b) class... or method still can't distinguish the two am not so good with theory. So i wrote this..
public static void main(String[] args) {
int a = 2;
int b = 31;
System.out.println(Math.pow(a, b));
}
Then i wanted to make my own Math.pow without using loops i wanted it to look more simple than loops, like using some type of Repeat I made a lot of research till i came across the commons-lang3 package i tried using StringUtils.repeat
So far I think this is the Syntax:-
public static String repeat(String str, int repeat)
StringUtils.repeat("ab", 2);
The problem i've been facing the past 24hrs or more is that StringUtils.repeat(String str, int 2); repeats strings not out puts or numbers or calculations.
Is there anything i can do to overcome this or is there any other better approach to creating a function that calculates powers?
without using loops or Math.pow
This might be funny but it took me while to figure out that StringUtils.repeat only repeats strings this is how i tried to overcome it. incase it helps
public static int repeat(int cal, int repeat){
cal = 2+2;
int result = StringUtils.repeat(cal,2);
return result;
}
can i not use recursion maybe some thing like this
public static RepeatThis(String a)
{
System.out.println(a);
RepeatThis(a);
}
just trying to understand java in dept thanks for all your comments even if there were syntax errors as long as the logic was understood that was good for me :)
Another implementation with O(Log(n)) complexity
public static long pow(long base, long exp){
if(exp ==0){
return 1;
}
if(exp ==1){
return base;
}
if(exp % 2 == 0){
long half = pow(base, exp/2);
return half * half;
}else{
long half = pow(base, (exp -1)/2);
return base * half * half;
}
}
Try with recursion:
int pow(int base, int power){
if(power == 0) return 1;
return base * pow(base, --power);
}
Function to handle +/- exponents with O(log(n)) complexity.
double power(double x, int n){
if(n==0)
return 1;
if(n<0){
x = 1.0/x;
n = -n;
}
double ret = power(x,n/2);
ret = ret * ret;
if(n%2!=0)
ret = ret * x;
return ret;
}
This one handles negative exponential:
public static double pow(double base, int e) {
int inc;
if(e <= 0) {
base = 1.0 / base;
inc = 1;
}
else {
inc = -1;
}
return doPow(base, e, inc);
}
private static double doPow(double base, int e, int inc) {
if(e == 0) {
return 1;
}
return base * doPow(base, e + inc, inc);
}
I think in Production recursion just does not provide high end performance.
double power(double num, int exponent)
{
double value=1;
int Originalexpn=exponent;
double OriginalNumber=num;
if(exponent==0)
return value;
if(exponent<0)
{
num=1/num;
exponent=abs(exponent);
}
while(exponent>0)
{
value*=num;
--exponent;
}
cout << OriginalNumber << " Raised to " << Originalexpn << " is " << value << endl;
return value;
}
Use this code.
public int mypow(int a, int e){
if(e == 1) return a;
return a * mypow(a,e-1);
}
Sure, create your own recursive function:
public static int repeat(int base, int exp) {
if (exp == 1) {
return base;
}
return base * repeat(base, exp - 1);
}
Math.pow(a, b)
Math is the class, pow is the method, a and b are the parameters.
Here is a O(log(n)) code that calculates the power of a number. Algorithmic technique used is divide and conquer. It also accepts negative powers i.e., x^(-y)
import java.util.Scanner;
public class PowerOfANumber{
public static void main(String args[]){
float result=0, base;
int power;
PowerOfANumber calcPower = new PowerOfANumber();
/* Get the user input for the base and power */
Scanner input = new Scanner(System.in);
System.out.println("Enter the base");
base=input.nextFloat();
System.out.println("Enter the power");
power=input.nextInt();
result = calcPower.calculatePower(base,power);
System.out.println(base + "^" + power + " is " +result);
}
private float calculatePower(float x, int y){
float temporary;
/* Termination condition for recursion */
if(y==0)
return 1;
temporary=calculatePower(x,y/2);
/* Check if the power is even */
if(y%2==0)
return (temporary * temporary);
else{
if(y>0)
return (x * temporary * temporary);
else
return (temporary*temporary)/x;
}
}
}
Remembering the definition of the logarithm, this can be done with ln and exp if these functions are allowed. Works for any positive base and any real exponent (not necessarily integer):
x = 6.7^4.4
ln(x) = 4.4 * ln(6.7) = about 8.36
x = exp(8.36) = about 4312.5
You can read more here and also here. Java provides both ln and exp.
A recursive method would be the easiest for this :
int power(int base, int exp) {
if (exp != 1) {
return (base * power(base, exp - 1));
} else {
return base;
}
}
where base is the number and exp is the exponenet

Categories

Resources