I'm told the following C code
#define ADD(a, b) a + b
// example function
void foo()
{
int i = ADD(1, 2); // add two ints
double d = //doubles
ADD(3.4, 5.6);
int sly = ADD(1, 2) * 3; // not what it appears to be
}
converts to this Java code
package demo;
public class DemoTranslation {
public static int add(int a, int b) {
return a + b;
}
public static double add(double a, double b) {
return a + b;
}
/**
* example function
*/
public static void foo() {
int i = add(1, 2); // add two ints
double d = /* doubles */ add(3.4, 5.6);
int sly = 1 + 2 * 3; // not what it appears to be
}
}
1+2*3 in java = 7. How does the C code produce that and not 9?
C macro replacement operates on lexical tokens, at a lower level than semantic analysis of the program.
Given #define ADD(a, b) a + b, the source text ADD(1, 2) * 3 is replaced by 1 + 2 * 3, which is evaluated as 1+(2•3) = 7.
Macro replacement was created for convenience in early primitive programming environments. As such, some of the motivation for developing it was simply typing convenience (editing source files could be a burdensome task in hardware of the era), and additional uses of it grew, including using macros to represent simple expressions. To deal with the fact that macros perform lexical substitution rather than semantic functions, C programmers have learned to parenthesize arguments in macro replacement lists as well as the entire list when macros are being used for expressions. So a C programmer would define ADD as:
#define ADD(a, b) ((a) + (b))
Then ADD(1, 2) * 3 will be replaced by ((1) + (2)) * 3, which will be evaluated as (1+2)•3 = 9.
Related
I am converting blocks of C code into Java, and I came across some syntax that I can not quite understand. The first one uses #define to create a function. I personally have not seen #define to create functions before. I also just found out in this post that this is really a macro. Below you will see what I attempted to interpret this code as in Java.
Here is the C code:
#define mat_elem(a, y, x, n) (a + ((y) * (n) + (x)))
Which I then converted to this in Java:
public double mat_elem(double a, int y, int x, int n){
return (a + ((y) * (n) + (x)));
}
Now the real issue here, is this block of code that also uses #define.
Code in C:
#define A(y, x) (*mat_elem(a, y, x, n))
I have not converted into Java yet because I'm not too sure what is going on.
I first thought that #define A(y, x) creates a data type that is equal to whatever get's returned in (*mat_elem(a, y, x, n)). However, the pointer that they are using in front of mat_elem is throwing me off.
I was thinking of doing something like this in Java:
public double[] fillA(double y, double x){
double [] A = new double [100];
for(int i = 0; i < some_var; i++){
A[i] = mat_elem(a, y, x, n);
}
return A;
}
I'm sure something like this would work, however my main concern is understanding what the C code is really doing, and If my imperfect code is equivalent to the code in C.
I do not like that C code much, but you work with what you got.
When you get something like this, your best bet to translating the C to the Java is to comment out the header includes and run it through the preprocessor and translate the preprocessed C code. See this answer for how to invoke the preprocessor: How do I run the GCC preprocessor to get the code after macros like #define are expanded?
In fact you only want to do this once, then work out what it's doing, and do the rest of the replacements intelligently, applying the logical meaning of the code rather than the direct meaning.
In this it expands to *(a + ((dia) * (n) + (dia)). ((dia) * (n) + (dia) is an integer, a pointer plus an integer is a pointer. Therefore, it ads this complex expression to the pointer and dereferences it. More commonly written as a[((dia) * (n) + (dia)].
Looks like the original C programmer was trying to construct a two dimensional array where the second dimension wasn't a constant. Arrays of arrays are idiomatic but this actually would be faster on most processors.
Both mat_elem and A are what are called function-like macros.
A macro is a simple text substitution. If you define a macro like
#define FOO a + b
then when the code is run through the preprocessor, every instance of FOO in the source code is replaced with the text a + b.
Function-like macros are similar, except that you can pass arguments to be expanded as well. If you write mat_elem(my_matrix, i, j, rows), then when the code is preprocessed that will be replaced with the text
(my_matrix + ((rows) * (i) + (j))
Note that macro arguments are not evaluated like function arguments - they are simply expanded in place. mat_elem(mat, i++, j+2, rows) will expand to
(mat + ((rows) * (i++) + (j+2))
Macros can invoke other macros. A(i, j) expands to (*mat_elem(a, y, x, n)), which in turn expands to
(*(a +((n) * (y) + (x)))
There is no equivalent facility in Java AFAIK - you will have to write methods to accomplish the same thing.
I am trying to create a function that generates a hash key based upon where in the hash table I want the value to go.
My hash function is (a + b * (key) ) % c = hash value. I've seen a similar question to this on SO, and what I tried is replacing b * (key) with d and just doing:
private int ReverseModulus(int a, int b, int c, int hashValue)
{
if(hashValue >= c)
return -1;
if(a < hashValue)
return (hashValue - a) / b;
return (c + hashValue - a) / b;
}
but it seems that most of the time hashValue != Hash(ReverseModulus(a,b,c, hashValue)).
I was wondering if the approach is wrong or if there is just an error in the code.
You're using the wrong kind of division. You're doing integer division, but you need to be doing modular division. In Java you can use BigInteger:
bh = new BigInteger(hashValue);
ba = new BigInteger(a);
bc = new BigInteger(c);
bn = bh.subtract(ba);
return bn.modInverse(bc).intValue();
and C# presumably has similar library functions.
I am trying to solve an given equation using Newton Tangent Method. The Tangent Method works by assuming the solution is somewhere in the a-b interval where a and b are given and that the function is continuous on the [a,b] interval.
I already wrote the program and it's working fine but now I have to make a GUI for it and the equation must be read from a text file.
My issues is that I do not know how to get the equation from the .txt file and set it as return for my function method. This should work for any given equation.
Below is my code for the equation: x^3 -4 * x^2 + 5 * x^1 -12
Here is the code:
static double f(double x) { // the function from the .txt file
//return Math.pow(x, 3) - 4* Math.pow(x,2) + 5 * Math.pow(x, 1) - 12;
return x * x * x - 4 * x * x + 5 * x - 12;
}
static double df(double x) { // the function derivative
return 3 * x * x - 8 * x + 5;
}
static String metTangent() {
double b = 4, c, reduceIntervalBy, precision = 0.00000000001;
// reduceIntervalBy holds the value of how much should the interval be reduced by, starting from b to a, so from right to left
DecimalFormat decimalformat = new DecimalFormat("#.00000000000000");
do {
c = b - f(b) / df(b);
//System.out.println(c);
reduceIntervalBy = b - c;
b = c;
} while (reduceIntervalBy > precision );
return "The solution is: " + decimalformat .format(c);
}
Solved it. Thanks everyone for help :)
you can use the below method to read the equation from a text file.
static String getEquation () throws Exception
{
Scanner in = new Scanner(new FileReader("C:\\test1.txt"));
StringBuffer br = new StringBuffer();
while(in.hasNext())
{
br.append(in.next());
}
return br.toString();
}
Then to parse the equation and value to be evaluated to the below function.
static Object f(double x,String eq) throws Exception {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
engine.put("x",x);
return engine.eval(eq);
}
To avoid having to write a parser, one can leverage an implementation of the Java Expression Language, e.g. https://uel.java.net/get-started.html. Alternatively, the Java Scripting API can do the same thing. Both is a little overkill for the small task but should quickly get you started.
Edit: See #robin's answer for an example using the scripting API.
I suspect this task is MUCH harder than you imagine, these are the basic steps you need to look at implementing:
Read the equation from a text file as a string
Write a parser to make some sort of structure of java objects from this string that represent a path to evaluate the equation for a given value. (this is the hard part - try looking for sources on 'descent parser' and 'shunting yard algorithm .
once you have this structure that can evaluate the equation for any x then the newton's method is easily implemented just as you do.
Good Luck
In what order does Java add up the numbers a + b + c?
Is it a + (b + c) or (a + b) + c?
I just learned how floating point representation works and finished an exercise which explained that if a, b, c are floats, they might yield a different result when added up in the different ways I wrote above.
That left me wondering which way Java actually does it?
The addition operator is left associative, meaning that a + b + c is evaluated the same as (a + b) + c.
The JLS, Section 15.18, states:
The additive operators have the same precedence and are syntactically left-associative (they group left-to-right).
Left to right (jls-15.18) unless you add parenthesis to alter the order of evaluation.
static int a() {
System.out.println("a");
return 1;
}
static int b() {
System.out.println("b");
return 1;
}
public static void main(String[] args) {
System.out.println(a() + b());
}
Output is
a
b
2
The order of a + b + c is that of (a + b) + c (left associativity).
I have the following statement:
long result = a * b * c;
This causes an overflow in the variable result. And so does:
long result = (long)a * b * c;
But the when broken down, they don't:
long result = a;
result *= b;
result *= c;
The type of a and b is int.
Can someone please explain why this is so? Does Java store the intermediate results in a temporary internal int variable in the first two cases?
Also do C and C++ behave the same way?
Assuming a * b * c fits in a long, but a * b does not fit in an int -
Your first snippet gives an overflow because a * b goes into a temporary int, as you suspected.
Your second snippet does NOT give an overflow, as you claim, because it is multiplying long values at each point.
Your third snippet doesn't give an overflow, because it is also multiplying long values at each point.
And, yes, C and C++ both work this way too; although depending on the platform, they may have different lengths for both int and long.
See the Oracle documentation for operator precedence.
Unary has higher precedence than multiplication, so (long)a*b*c is (long)(a)*b*c.
Same in C++.
I just tested these programs:
public class JavaApplication2 {
public static void main(String[] args) {
long l = (long)Integer.MAX_VALUE;
l *= 2;
l *= 2;
System.out.println(l);
}
}
and
public class JavaApplication2 {
public static void main(String[] args) {
long l = (long)Integer.MAX_VALUE*2*2;
System.out.println(l);
}
}
They show the exact same output.
In contrast, remove the cast in the second version and you get an overflow.