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)
Related
public static double calculatePower (double x, int y) {
if (y == 0)
return 1;
else
return (int) calculatePower(x, y-1);
I understand how the recrusive function is called, but not how it is cancelled.
I think, if at some point y=1 the function should return 1 because of the if statement.
But it does not and I do not understand why
For every recursive invocation the incoming y parameter is reduced by one since you write calculatePower(x, y-1);. At some point y is 0 and the recursion stops.
Note that your power calculation is wrong , you should add a x * before the actual recursive call: x * calculatePower(x, y-1)
This will subtract 1 from y every time it gets executed.
I recommend you execute it manually on paper to see how the program works.
ex: calculatepower(2,3) -> calculatepower(2,2) -> calculatepower(2,1) -> calculatepower(2,0). Now since y = 0 the if statement will get executed and it will return 1
Your function will only return the value 1 though (if y was a positive number)
This youtube tutorial will give you a clear explanation for recursion:
https://www.youtube.com/watch?v=neuDuf_i8Sg
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);
I have a program in Java that generates a float value aggressiveness that can be from 0 to infinite. What I need to do is that the higher this float is, the higher there are chances the program fires a function attackPawn().
I already found out that I need the function Math.random(), which gives a random value between 0 and 1. If Math.random() is lower than aggressiveness transformed into a float between 0 and 1, I call the function attackPawn().
But now I am stuck, I can't figure out how I can transform aggressiveness from 0 to infinite to a float which is from 0 to 1, 1 meaning "infinite" aggressiveness and 0 meaning absence of anger.
Any ideas or math equation?
You want a monotonic function that maps [0...infinity] to [0..1]. There are many options:
y=Math.atan(x)/(Math.PI/2);
y=x/(1+x);
y=1-Math.exp(-x);
There are more. And each of those functions can be scaled arbitrarily, given a positive constant k>0:
y=Math.atan(k*x)/(Math.PI/2);
y=x/(k+x);
y=1-Math.exp(-k*x);
There is an infinite number of options. Just pick one that suits your needs.
It is possible to map [0,infinity) to [0,1), but this won't be linear. An example function would be:
y = tan(x * pi / 2);
The problem with this function is that you can't make a correct computer program from that since it is not possible (or easy) to first compute a real big number like 10^5000 and map it down to [0,1).
But a better solution would be to change your definition to something like that:
0 = no aggression
1 = maximum aggression
With this you don't have to map the numbers
Try something like this:
// aggressiveness is a float with a value between 0 and Float.MAX_VALUE or a value of Float.POSITIVE_INFINITY
if (aggressiveness == Float.POSITIVE_INFINITY) {
aggressiveness = 1f;
} else {
aggressiveness = aggressiveness / Float.MAX_VALUE;
}
// aggressiveness is now between 0 and 1 (inclusive)
Though Double class supports infinite value double d=Double.POSITIVE_INFINITY but i dont think you can use it for your arithmatic purpose. Better you define a maximum value and treat it as infinity.
double Min=0;
double Max= Double.MAX_VALUE;
double aggresiveness= Min + (Math.random() * ((Max - Min) + 1));
ps: you can also take aggresiveness as long or int if you don't want it be a double
Try to transform aggressiveness with a function like:
public float function(float aggressiveness) {
if(aggressiveness > 0F) {
return 1 - (1 / aggressiveness);
}
return 0F;
}
This will map your value to the range of [0, 1);
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
I'm doing some small program for a beginners programming course and in my program I have 2 variables which hold numbers. Anyway I need to find out which number is bigger and print the appropriate message according to it, for example I have:
int x = 5;
int y = 10;
I need to print:
"it is true that y is bigger than x";
Now the thing is that I know I can use a simple if statement but I'm not allowed to use it, now it makes me wonder, is it even possible? If so, how can I do that? How can I check which number is bigger WITHOUT doing something like:
if (x > y)
answer = true;
...
Thanks in advance.
Well you can do:
boolean answer = x > y;
The expression x > y is just an expression of type boolean. While boolean expressions are often used for conditions in if statements, loops etc, they don't have to be - simple assignment works fine too.
It sounds like you want the reverse though:
boolean answer = y > x;
Then you can use the value of answer to build the string to display...
Use the ternary operator:
System.out.println(x > y ? "It is true that x is greater than y" : "");
ternary operator "?:"
String output = (x > y)? "x is greater than y":"y is greater than x";
The ternary conditional operator that others mentioned will work. Assuming you are looking for creative ways to do this rather than practical ones, here's another method:
int x = 5;
int y = 10;
while(y > x){
System.out.println("It is true that y is bigger than x.");
return;
}
System.out.println("It is false that y is bigger than x.");
The while is just acting as a fancy if, because the return means the otherwise infinite loop will only execute at most once.
Here's another example that instead relies upon short-circuit boolean evaluation:
public static void main(String...args){
int x = 5;
int y = 10;
boolean answer = (y > x);
boolean testTrue = answer && printTrue();
boolean testFalse = testTrue || printFalse();
}
private static boolean printFalse() {
System.out.println("It is false that y is bigger than x.");
return true;
}
private static boolean printTrue() {
System.out.println("It is true that y is bigger than x.");
return true;
}
Of course you shouldn't do this in real production code, but it can be fun to think of unorthodox ways to code something and it can be helpful for exploring the language.
Your question is tagged as Java but you do not specify Java in your question. In Java there are multiple ways to get the same result that involve testing the boolean expression x > y somehow, such as the ternary operator. I would consider these equivalent to an explicit if statement.
Other possibilities:
Compute the square root of x - y. This will raise an exception if y is bigger. Catch the exception in the caller and report that y is the larger quantity. If there is no exception, report that x is the larger.
In LISP, Ruby or another language that supports the symbol type, form a list ((symbol x, x), (symbol y, y)) and sort the list. Then report the second symbol as the variable with the larger value.
If using assembly, BASIC, PL/1, etc. you can use an arithmetic expression to choose the target of a GOTO statement. Depending on whether x or y is larger, execution will resume at a different part of the code. Or use the list-sorting trick in the previous bullet to select the GOTO label.
In general, the expression ((x - y) / abs(x - y) + 1) / 2 will produce 1 if x is larger and 0 if y is larger. This result could be used to choose data, a function, etc. out of a list of two alternatives, producing conditional behavior without an if statement.
You could use recursion (but I would not recommend it)
public int compare ( int a , int b )
{
switch ( a )
{
case Integer.MIN_VALUE :
switch ( b )
{
case Integer.MIN_VALUE :
return 0 ;
default :
return -1 ;
}
default :
switch ( b )
{
case INteger.Min_VALUE :
return 1 ;
default :
return compare ( a-1 , b-1 ) ;
}
}
}
(a+b)/2 + Abs(a-b)/2 is the bigger number.
I know in some languages you can use short-circuit evaluation to construct the answer.
The expression (A && B) always evaluates to B if A is true. If A is false then B is never evaluated.
Similarly (A || B) evaluates to B if A is false. If A is true B is never evaluated.
Though I'm not 100% sure of Java, the expression you want is:
String output = ((x > y) && "it is true that X is greater than Y")
|| (((x < y) && "it is true that X is less than Y")
|| "it is true that X is equal to Y");