Normalize value from [-x|x] to [-1|1] - java

I want to normalize a value between -x and x to -1 and 1.
I thought about value / Math.abs(value), but the problem is if
value is 0 that doesn't work.
Is there a possibility without if and else, so with one operation?
Maybe i should add, that the value only can be -x, x, or 0. nothing between.

value / Math.abs(x)
is what you need. x should never be zero obviously.
Also you should think how to handle the case when value > x.

Take a look at the java.lang.Integer class. There are some nice static methods to help you out, mainly Integer.signum(int)
That will do the job, if you want 0 to convert to 1 too, add a check for 0:
int x = value == 0 ? 1 : Integer.signum(value);
Edit: Long contains likewise methods that do the job with long.
Alternately, no-if code; probably slower, but OP specifically asked for it:
final static int[] TABLE = { -1, 1 (or 0), 1 };
int x = TABLE[Integer.signum(value) + 1];

Lets assume you only want the sign of the number. You can use
double sign = Math.signum(x);
Note: this return NaN for NaN and 0 for 0.
If you expect 0 to return a different value there alternatives.
Note: a condition might be simpler/clearer. e.g.
int sign = x < 0 ? -1 : +1;
or
int sign = x > 0 ? +1 : x < 0 : -1 : 0;

Here's a mathematic method, I started from -5 to 5 and converted in -1 to 1
max=1;
min=-1;
maxold=-5;
minold=5;
value=2;
newvalue= (max-min)/(maxold-minold)*(value-minold)+min;
alert(newvalue);

Related

How to find the closest value of 2^N to a given input?

I somehow have to keep my program running until the output of the exponent function exceeds the input value, and then compare that to the previous output of the exponent function. How would I do something like that, even if in just pseudocode?
Find logarithm to base 2 from given number => x := log (2, input)
Round the value acquired in step 1 both up and down => y := round(x), z := round(x) + 1
Find 2^y, 2^z, compare them both with input and choose the one that suits better
Depending on which language you're using, you can do this easily using bitwise operations. You want either the value with a single 1 bit set greater than the highest one bit set in the input value, or the value with the highest one bit set in the input value.
If you do set all of the bits below the highest set bit to 1, then add one you end up with the next greater power of two. You can right shift this to get the next lower power of two and choose the closer of the two.
unsigned closest_power_of_two(unsigned value)
{
unsigned above = (value - 1); // handle case where input is a power of two
above |= above >> 1; // set all of the bits below the highest bit
above |= above >> 2;
above |= above >> 4;
above |= above >> 8;
above |= above >> 16;
++above; // add one, carrying all the way through
// leaving only one bit set.
unsigned below = above >> 1; // find the next lower power of two.
return (above - value) < (value - below) ? above : below;
}
See Bit Twiddling Hacks for other similar tricks.
Apart from the looping there's also one solution that may be faster depending on how the compiler maps the nlz instruction:
public int nextPowerOfTwo(int val) {
return 1 << (32 - Integer.numberOfLeadingZeros(val - 1));
}
No explicit looping and certainly more efficient than the solutions using Math.pow. Hard to say more without looking what code the compiler generates for numberOfLeadingZeros.
With that we can then easily get the lower power of 2 and then compare which one is nearer - the last part has to be done for each solution it seems to me.
set x to 1.
while x < target, set x = 2 * x
then just return x or x / 2, whichever is closer to the target.
public static int neareastPower2(int in) {
if (in <= 1) {
return 1;
}
int result = 2;
while (in > 3) {
in = in >> 1;
result = result << 1;
}
if (in == 3) {
return result << 1;
} else {
return result;
}
}
I will use 5 as input for an easy example instead of 50.
Convert the input to bits/bytes, in this case 101
Since you are looking for powers of two, your answer will all be of the form 10000...00 (a one with a certain amount of zeros). You take the input value (3 bits) and calculate the integer value of 100 (3 bits) and 1000 (4 bits). The integer 100 will be smaller then the input, the integer 1000 will be larger.
You calculate the difference between the input and the two possible values and use the smallest one. In this case 100 = 4 (difference of 1) while 1000 = 8 (difference of 3), so the searched answer is 4
public static int neareastPower2(int in) {
return (int) Math.pow(2, Math.round(Math.log(in) / Math.log(2)));
}
Here's the pseudo code for a function that takes the input number and returns your answer.
int findit( int x) {
int a = int(log(x)/log(2));
if(x >= 2^a + 2^(a-1))
return 2^(a+1)
else
return 2^a
}
Here's a bitwise solution--it will return the lessor of 2^N and 2^(N+1) in case of a tie. This should be very fast compare to invoking the log() function
let mask = (~0 >> 1) + 1
while ( mask > value )
mask >> 1
return ( mask & value == 0 ) ? mask : mask << 1

In Java, how do I create a bitmap to solve "knapsack quandary"

I'm in my first programming course and I'm quite stuck right now. Basically, what we are doing is we take 16 values from a text file (on the first line of code) and there is a single value on the second line of code. We read those 16 values into an array, and we set that 2nd line value as our target. I had no problem with that part.
But, where I'm having trouble is creating a bitmap to test every possible subset of the 16 values, that equal the target number.
IE, say we had these numbers:
12 15 20 4 3 10 17 12 24 21 19 33 27 11 25 32
We then correspond each value to a bitmap
0 1 1 0 0 0 0 1 1 1 0 1 0 0 1 0
Then we only accept the values predicated with "1"
15 20 12 24 21 33 25
Then we test that subset to see if it equals the "target" number.
We are only allowed to use one array in the problem, and we aren't allowed to use the math class (haven't gotten to it yet).
I understand the concept, and I know that I need to implement shifting operators and the logical & sign, but I'm truly at a loss. I'm very frustrated, and I just was wondering if anybody could give me any tips.
To generate all possible bit patterns inside an int and thus all possible subsets defined by that bit map would simply require you to start your int at 1 and keep incrementing it to the highest possible value an unsigned short int can hold (all 1s). At the end of each inner loop, compare the sum to the target. If it matches, you got a solution subset - print it out. If not, try the next subset.
Can someone help to explain how to go about doing this? I understand the concept but lack the knowledge of how to implement it.
OK, so you are allowed one array. Presumably, that array holds the first set of data.
So your approach needs to not have any additional arrays.
The bit-vector is simply a mental model construct in this case. The idea is this: if you try every possible combination (note, NOT permutation), then you are going to find the closest sum to your target. So lets say you have N numbers. That means you have 2^N possible combinations.
The bit-vector approach is to number each combination with 0 to 2^N - 1, and try each one.
Assuming you have less that 32 numbers in the array, you essentially have an outer loop like this:
int numberOfCombinations = (1 << numbers.length - 1) - 1;
for (int i = 0; i < numberOfCombinations; ++i) { ... }
for each value of i, you need to go over each number in numbers, deciding to add or skip based on shifts and bitmasks of i.
So the task is to what an algorithm that, given a set A of non-negative numbers and a goal value k, determines whether there is a subset of A such that the sum of its elements is k.
I'd approach this using induction over A, keeping track of which numbers <= k are sums of a subset of the set of elements processed so far. That is:
boolean[] reachable = new boolean[k+1];
reachable[0] = true;
for (int a : A) {
// compute the new reachable
// hint: what's the relationship between subsets of S and S \/ {a} ?
}
return reachable[k];
A bitmap is, mathematically speaking, a function mapping a range of numbers onto {0, 1}. A boolean[] maps array indices to booleans. So one could call a boolean[] a bitmap.
One disadvanatage of using a boolean[] is that you must process each array element individually. Instead, one could use that a long holds 64 bits, and use bitshifting and masking operations to process 64 "array" elements at a time. But that sort of microoptimization is error-prone and rather involved, so not commonly done in code that should be reliable and maintainable.
I think you need something like this:
public boolean equalsTarget( int bitmap, int [] numbers, int target ) {
int sum = 0; // this is the variable we're storing the running sum of our numbers
int mask = 1; // this is the bitmask that we're using to query the bitmap
for( int i = 0; i < numbers.length; i++ ) { // for each number in our array
if( bitmap & mask > 0 ) { // test if the ith bit is 1
sum += numbers[ i ]; // and add the ith number to the sum if it is
}
mask <<= 1; // shift the mask bit left by 1
}
return sum == target; //if the sum equals the target, this bitmap is a match
}
The rest of your code is fairly simple, you just feed every possible value of your bitmap (1..65535) into this method and act on the result.
P.s.: Please make sure that you fully understand the solution and not just copy it, otherwise you're just cheating yourself. :)
P.p.s: Using int works in this case, as int is 32 bit wide and we only need 16. Be careful with bitwise operations though if you need all the bits, as all primitive integer types (byte, short, int, long) are signed in Java.
There are a couple steps in solving this. First you need to enumerate all the possible bit maps. As others have pointed out you can do this easily by incrementing an integer from 0 to 2^n - 1.
Once you have that, you can iterate over all the possible bit maps you just need a way to take that bit map and "apply" it to an array to generate the sum of the elements at all indexes represented by the map. The following method is an example of how to do that:
private static int bitmapSum(int[] input, int bitmap) {
// a variable for holding the running total
int sum = 0;
// iterate over each element in our array
// adding only the values specified by the bitmap
for (int i = 0; i < input.length; i++) {
int mask = 1 << i;
if ((bitmap & mask) != 0) {
// If the index is part of the bitmap, add it to the total;
sum += input[i];
}
}
return sum;
}
This function will take an integer array and a bit map (represented as an integer) and return the sum of all the elements in the array whose index are present in the mask.
The key to this function is the ability to determine if a given index is in fact in the bit map. That is accomplished by first creating a bit mask for the desired index and then applying that mask to the bit map to test if that value is set.
Basically we want to build an integer where only one bit is set and all the others are zero. We can then bitwise AND that mask with the bit map and test if a particular position is set by comparing the result to 0.
Lets say we have an 8-bit map like the following:
map: 1 0 0 1 1 1 0 1
---------------
indexes: 7 6 5 4 3 2 1 0
To test the value for index 4 we would need a bit mask that looks like the following:
mask: 0 0 0 1 0 0 0 0
---------------
indexes: 7 6 5 4 3 2 1 0
To build the mask we simply start with 1 and shift it by N:
1: 0 0 0 0 0 0 0 1
shift by 1: 0 0 0 0 0 0 1 0
shift by 2: 0 0 0 0 0 1 0 0
shift by 3: 0 0 0 0 1 0 0 0
shift by 4: 0 0 0 1 0 0 0 0
Once we have this we can apply the mask to the map and see if the value is set:
map: 1 0 0 1 1 1 0 1
mask: 0 0 0 1 0 0 0 0
---------------
result of AND: 0 0 0 1 0 0 0 0
Since the result is != 0 we can tell that index 4 is included in the map.

How to code a selector?

I am working on a algorithm but there is a note about a selector. I am not sure what this means but the research paper I am working says:
δ () is a selector, i.e. δ (x) =1 if x>0, else
δ (x) = 0 ;
How does one code this using pseudo code, c++, or Java?
Thanks
δ () is a selector, i.e. δ (x) =1 if x>0, else δ (x) = 0
You just need an if
In pseudocode:
delta = function(x)
{
if (x > 0)
return 1
else
return 0
}
this is a function
pass in x
check if x > 0
if so, return 1
otherwise
return 0
template <class T>
int selector(T x)
{
return x > 0 ? 1 : 0;
}
A selector in this context is simply a boolean function which returns 0 (or 1) for all values of x up to a certain point, and then return 1 (or 0) there after. In other words, a two-steps step function.
BTW, given the specific definition of delta in the question, delta is the discrete Heaviside Step Function with a value of 0 for x = 0.
If you don't want to use an if, you could write (in C#):
Math.Ceiling(Math.Sign(x) * 0.1)
In Java it should be something like this:
Math.ceiling(Math.signum(x) * 0.1)

What Java method takes an int and returns +1 or -1?

What Java method takes an int and returns +1 or -1? The criteria for this is whether or not the int is positive or negative. I looked through the documentation but I'm bad at reading it and I can't find it. I know I've seen it somewhere though.
Integer.signum(int i)
Math.signum(value) will do the trick but since it returns float or double (according to parameter) you will have to cast it:
int sign = (int)Math.signum(value);
or:
Integer.signum(value);
Strictly evaluating to -1 or 1, and cooler (probably more efficient too) than n < 0 ? -1: 1:
(n >> 31) | 1
In case you want to use it for long too:
(n >> 63) | 1
Use Integer.signum(int i), but if you want a custom in-line bit of code:
int ans = i < 0 ? -1 : 1;
if you want 0 also:
int ans = i == 0 ? 0 : (i < 0 ? -1 : 1);
Math.signum(double i)
Returns the signum function of the argument; zero if the argument is zero, 1.0 if the argument is greater than zero, -1.0 if the argument is less than zero.
Special Cases:
If the argument is NaN, then the result is NaN.
If the argument is positive zero or negative zero, then the result is the same as the argument.
Parameters:
d - the floating-point value whose signum is to be returned
Returns: The signum function of the argument
Since: 1.5
For fun:
return (i > 0) ? 1 : ( (i < 0) ? -1 : 0 );

Make a negative number positive

I have a Java method in which I'm summing a set of numbers. However, I want any negatives numbers to be treated as positives. So (1)+(2)+(1)+(-1) should equal 5.
I'm sure there is very easy way of doing this - I just don't know how.
Just call Math.abs. For example:
int x = Math.abs(-5);
Which will set x to 5.
Note that if you pass Integer.MIN_VALUE, the same value (still negative) will be returned, as the range of int does not allow the positive equivalent to be represented.
The concept you are describing is called "absolute value", and Java has a function called Math.abs to do it for you. Or you could avoid the function call and do it yourself:
number = (number < 0 ? -number : number);
or
if (number < 0)
number = -number;
You're looking for absolute value, mate. Math.abs(-5) returns 5...
Use the abs function:
int sum=0;
for(Integer i : container)
sum+=Math.abs(i);
Try this (the negative in front of the x is valid since it is a unary operator, find more here):
int answer = -x;
With this, you can turn a positive to a negative and a negative to a positive.
However, if you want to only make a negative number positive then try this:
int answer = Math.abs(x);
A little cool math trick! Squaring the number will guarantee a positive value of x^2, and then, taking the square root will get you to the absolute value of x:
int answer = Math.sqrt(Math.pow(x, 2));
Hope it helps! Good Luck!
This code is not safe to be called on positive numbers.
int x = -20
int y = x + (2*(-1*x));
// Therefore y = -20 + (40) = 20
Are you asking about absolute values?
Math.abs(...) is the function you probably want.
You want to wrap each number into Math.abs(). e.g.
System.out.println(Math.abs(-1));
prints out "1".
If you want to avoid writing the Math.-part, you can include the Math util statically. Just write
import static java.lang.Math.abs;
along with your imports, and you can refer to the abs()-function just by writing
System.out.println(abs(-1));
The easiest, if verbose way to do this is to wrap each number in a Math.abs() call, so you would add:
Math.abs(1) + Math.abs(2) + Math.abs(1) + Math.abs(-1)
with logic changes to reflect how your code is structured. Verbose, perhaps, but it does what you want.
When you need to represent a value without the concept of a loss or absence (negative value), that is called "absolute value".
The logic to obtain the absolute value is very simple: "If it's positive, maintain it. If it's negative, negate it".
What this means is that your logic and code should work like the following:
//If value is negative...
if ( value < 0 ) {
//...negate it (make it a negative negative-value, thus a positive value).
value = negate(value);
}
There are 2 ways you can negate a value:
By, well, negating it's value: value = (-value);
By multiplying it by "100% negative", or "-1": value = value *
(-1);
Both are actually two sides of the same coin. It's just that you usually don't remember that value = (-value); is actually value = 1 * (-value);.
Well, as for how you actually do it in Java, it's very simple, because Java already provides a function for that, in the Math class: value = Math.abs(value);
Yes, doing it without Math.abs() is just a line of code with very simple math, but why make your code look ugly? Just use Java's provided Math.abs() function! They provide it for a reason!
If you absolutely need to skip the function, you can use value = (value < 0) ? (-value) : value;, which is simply a more compact version of the code I mentioned in the logic (3rd) section, using the Ternary operator (? :).
Additionally, there might be situations where you want to always represent loss or absence within a function that might receive both positive and negative values.
Instead of doing some complicated check, you can simply get the absolute value, and negate it: negativeValue = (-Math.abs(value));
With that in mind, and considering a case with a sum of multiple numbers such as yours, it would be a nice idea to implement a function:
int getSumOfAllAbsolutes(int[] values){
int total = 0;
for(int i=0; i<values.lenght; i++){
total += Math.abs(values[i]);
}
return total;
}
Depending on the probability you might need related code again, it might also be a good idea to add them to your own "utils" library, splitting such functions into their core components first, and maintaining the final function simply as a nest of calls to the core components' now-split functions:
int[] makeAllAbsolute(int[] values){
//#TIP: You can also make a reference-based version of this function, so that allocating 'absolutes[]' is not needed, thus optimizing.
int[] absolutes = values.clone();
for(int i=0; i<values.lenght; i++){
absolutes[i] = Math.abs(values[i]);
}
return absolutes;
}
int getSumOfAllValues(int[] values){
int total = 0;
for(int i=0; i<values.lenght; i++){
total += values[i];
}
return total;
}
int getSumOfAllAbsolutes(int[] values){
return getSumOfAllValues(makeAllAbsolute(values));
}
Why don't you multiply that number with -1?
Like This:
//Given x as the number, if x is less than 0, return 0 - x, otherwise return x:
return (x <= 0.0F) ? 0.0F - x : x;
If you're interested in the mechanics of two's complement, here's the absolutely inefficient, but illustrative low-level way this is made:
private static int makeAbsolute(int number){
if(number >=0){
return number;
} else{
return (~number)+1;
}
}
Library function Math.abs() can be used.
Math.abs() returns the absolute value of the argument
if the argument is negative, it returns the negation of the argument.
if the argument is positive, it returns the number as it is.
e.g:
int x=-5;
System.out.println(Math.abs(x));
Output: 5
int y=6;
System.out.println(Math.abs(y));
Output: 6
String s = "-1139627840";
BigInteger bg1 = new BigInteger(s);
System.out.println(bg1.abs());
Alternatively:
int i = -123;
System.out.println(Math.abs(i));
To convert negative number to positive number (this is called absolute value), uses Math.abs(). This Math.abs() method is work like this
“number = (number < 0 ? -number : number);".
In below example, Math.abs(-1) will convert the negative number 1 to positive 1.
example
public static void main(String[] args) {
int total = 1 + 1 + 1 + 1 + (-1);
//output 3
System.out.println("Total : " + total);
int total2 = 1 + 1 + 1 + 1 + Math.abs(-1);
//output 5
System.out.println("Total 2 (absolute value) : " + total2);
}
Output
Total : 3
Total 2 (absolute value) : 5
I would recommend the following solutions:
without lib fun:
value = (value*value)/value
(The above does not actually work.)
with lib fun:
value = Math.abs(value);
I needed the absolute value of a long , and looked deeply into Math.abs and found that if my argument is less than LONG.MIN_VAL which is -9223372036854775808l, then the abs function would not return an absolute value but only the minimum value. Inthis case if your code is using this abs value further then there might be an issue.
Can you please try this one?
public static int toPositive(int number) {
return number & 0x7fffffff;
}
if(arr[i]<0)
Math.abs(arr[i]); //1st way (taking absolute value)
arr[i]=-(arr[i]); //2nd way (taking -ve of -ve no. yields a +ve no.)
arr[i]= ~(arr[i]-1); //3rd way (taking negation)
I see people are saying that Math.abs(number) but this method is not full proof.
This fails when you try to wrap Math.abs(Integer.MIN_VALUE) (see ref. https://youtu.be/IWrpDP-ad7g)
If you are not sure whether you are going to receive the Integer.MIN_VALUE in the input. It is always recommended to check for that number and handle it manually.
In kotlin you can use unaryPlus
input = input.unaryPlus()
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-int/unary-plus.html
Try this in the for loop:
sum += Math.abs(arr[i])
dont do this
number = (number < 0 ? -number : number);
or
if (number < 0) number = -number;
this will be an bug when you run find bug on your code it will report it as RV_NEGATING_RESULT_OF

Categories