Groovy primitive double arithmetic - groovy

This yields 127
double middle = 255 / 2
While this yields 127.5
Double middle = 255 / 2
Meanwhile this yields 127.5 as well
double middle = (255 / 2) as double
I know that Groovy operates with BigDecimal per default, but to me this is a Huuge bug! How can this be?

This actually has nothing to do with BigDecimals, but rather with the type coercion from primitive integer to the primitive double. This problem is caused by the Groovy compiler and the (most probably) incorrect bytecode it produces. Take a look at the following bytecode representation of the first case. The following Groovy code:
void ex1() {
double x = 255 / 2
println x
}
gets compiled to a bytecode that can be represented as:
public void ex1() {
CallSite[] var1 = $getCallSiteArray();
double x = 0.0D;
if (BytecodeInterface8.isOrigInt() && BytecodeInterface8.isOrigD() && !__$stMC && !BytecodeInterface8.disabledStandardMetaClass()) {
int var5 = 255 / 2;
x = (double)var5;
} else {
Object var4 = var1[5].call(255, 2);
x = DefaultTypeTransformation.doubleUnbox(var4);
}
var1[6].callCurrent(this, x);
}
It shows that in this case, it is not possible to get 127.5 as a result, because the result of 255 / 2 expression is stored in the variable of type int. It feels like this is an example of inconsistent behavior because here is what the bytecode of the method that uses Double looks like:
public void ex2() {
CallSite[] var1 = $getCallSiteArray();
Double x = null;
if (BytecodeInterface8.isOrigInt() && !__$stMC && !BytecodeInterface8.disabledStandardMetaClass()) {
Object var4 = var1[8].call(255, 2);
x = (Double)ScriptBytecodeAdapter.castToType(var4, Double.class);
} else {
Object var3 = var1[7].call(255, 2);
x = (Double)ScriptBytecodeAdapter.castToType(var3, Double.class);
}
var1[9].callCurrent(this, x);
}
The main problem with this use case is that adding #TypeChecked does not prevent you from making this mistake - compilation passes and the incorrect result is returned. However, when we add #TypeChecked annotation to the method that uses Double the compilation error is thrown. Adding #CompileStatic solves the problem.
I've run some tests and I can confirm that this problem exists in the recent 2.5.6, as well as 3.0.0-alpha-4 versions. I've created a bug report in the Groovy JIRA project. Thanks for finding and reporting the problem!
UPDATE: Java does the same
It seems like this is not a Groovy bug - this is how Java does things as well. In Java, you can store a result of a division of two ints in the double variable, but you will get nothing else than an integer cast to the double. With {{Double}} type things are different in terms of the syntax but pretty similar in terms of the bytecode. With {{Double}} you need to explicitly cast at least one part of the equation to the {{double}} type, which results in the bytecode that casts both integers to the {{double}}. Consider the following example in Java:
final class IntDivEx {
static double div(int a, int b) {
return a / b;
}
static Double div2(int a, int b) {
return a / (double) b;
}
public static void main(String[] args) {
System.out.println(div(255,2));
System.out.println(div2(255,2));
}
}
When you run it you get:
127.0
127.5
Now, if you take a look at the bytecode it creates, you will see something like this:
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
final class IntDivEx {
IntDivEx() {
}
static double div(int a, int b) {
return (double)(a / b);
}
static Double div2(int a, int b) {
return (double)a / (double)b;
}
public static void main(String[] args) {
System.out.println(div(255, 2));
System.out.println(div2(255, 2));
}
}
The only difference (in terms of the syntax) between Groovy and Java is that Groovy allows you to implicitly cast an integer to Double, and that is why
Double x = 255 / 2
is the correct statement in Groovy, while Java, in this case, fails during the compilation with the following error:
Error:(10, 18) java: incompatible types: int cannot be converted to java.lang.Double
That is why in Java you need to use casting when you assign from integer to Double.

Related

Java Concept Confusion : Objects and Primitive Types

I am really confused about this concept:
/* Example with primitive data type */
public class Example1 {
public static void main (String[] args){
int a = 1;
System.out.println("a is " + a);
myMethod( a );
System.out.println("a is " + a);
}
public static void myMethod(int b){
b = 3;
System.out.println("b is " + b);
}
}
OUTPUT:
a is 1
b is 3
a is 1
Why does "a" not change?How does this primitive variable CHANGE like for a FOR LOOP or a WHILE LOOP when int i is initialed to zero? Like this:
int i = 1;
while (i < = 3) {
System.out.println(i);
i *= 2;
}
OUTPUT:
1
2
Please let me know in detail, as I am really confused.i is a primitive type, why does it get updated, and why does not int a in the first program?
myMethod() is void, if it returned an int and you assigned a=myMethod(a) then it would change
int a = 1;
System.out.println("a is " + a);
a= myMethod(a); //where myMethod is changed to return b instead of void
System.out.println("a is " + a);
a is 1
b is 3
a is 3
"Why does "a" not change?"
Because primitive a inside of your myMethod is not the same a that you had in your void main. Treat it as completely another variable and that its value got copied into myMethod. This primitive`s lifecycle ends in the end of this method execution.
If you have C++ background then maybe this explanation might help:
When you pass primitive type arguments into method - you are passing
variables that are being copied. You passed value, not instance.
When you pass objects as arguments
into method - you are passing references to that object, but to be more precise: in java, a copy of reference value is being passed. It is like passing a copy of the address of the object to the method. If you modify this object inside this method, the modifications will be visible outside the method. If you =null or =new Obj it, it will affect the object only inside your method.

How does type promotion work in Groovy?

Consider the following code snippet -
def factorial(number) {
if(number == 1)
return number;
else
return number * factorial(number - 1);
}
println factorial(50)
println factorial(50).getClass()
println()
println 45**20
println ((45**20).getClass())
The output is -
0
class java.lang.Integer
1159445329576199417209625244140625
class java.math.BigInteger
Questions -
Why doesn't groovy automatically promote the result of number * factorial(number-1) to a BigInt in the first case?
Why is the output 0? Why isn't it some random number that we should get after integer overflow?
Old question but I'll try to answer both parts of the question:
Groovy documentation on arithmetic operations states that
binary operations involving subclasses of java.lang.Number automatically convert their arguments according to the following matrix (except for division, which is discussed below)
I won't paste the matrix but it specifies no casting to BigInteger or BigDecimal unless one of the operators is of one of these types.
In the case of division:
The division operators "/" and "/=" produce a Double result if either operand is either Float or Double and a BigDecimal result otherwise
I think that the table is not considering the power operator (**) since it's not present in Java and as stated in #tim_yates comment, power implementation uses BigInteger by default.
The code in DefaultGroovyMethods.java shows clearly that the power of int's is calculated using BigInteger's and if the result is small then is cast down to int again (And that's why (2**4).class is java.lang.Integer):
public static Number power(Integer self, Integer exponent) {
if (exponent >= 0) {
BigInteger answer = BigInteger.valueOf(self).pow(exponent);
if (answer.compareTo(BI_INT_MIN) >= 0 && answer.compareTo(BI_INT_MAX) <= 0) {
return answer.intValue();
} else {
return answer;
}
} else {
return power(self, (double) exponent);
}
}
To confirm the behaviour of other operations you can go to IntegerMath, LongMath or other classes in the org.codehaus.groovy.runtime.typehandling package
With Groovy, Integer.multiply( Integer ) always returns an Integer.
The factorial method starts overflowing around step 16.
At step 34, you end up with -2147483648 * -2147483648 which returns 0 so the result will always be 0
One fix is to change your method declaration to:
def factorial( BigInteger number ) {

How do I use groovy's AS keyword

This may be a duplicate but "as" is an INCREDABLY hard keyword to google, even S.O. ignores "as" as part of query.
So I'm wondering how to implement a class that supports "as" reflexively. For an example class:
class X {
private val
public X(def v) {
val=v
}
public asType(Class c) {
if (c == Integer.class)
return val as Integer
if(c == String.class)
return val as String
}
}
This allows something like:
new X(3) as String
to work, but doesn't help with:
3 as X
I probably have to attach/modify the "asType" on String and Integer somehow, but I feel any changes like this should be confined to the "X" class... Can the X class either implement a method like:
X fromObject(object)
or somehow modify the String/Integer class from within X. This seems tough since it won't execute any code in X until X is actually used... what if my first usage of X is "3 as X", will X get a chance to override Integer's asType before Groovy tries to call is?
As you say, it's not going to be easy to change the asType method for Integer to accept X as a new type of transformation (especially without destroying the existing functionality).
The best I can think of is to do:
Integer.metaClass.toX = { -> new X( delegate ) }
And then you can call:
3.toX()
I can't think how 3 as X could be done -- as you say, the other way; new X('3') as Integer is relatively easy.
Actually, you can do this:
// Get a handle on the old `asType` method for Integer
def oldAsType = Integer.metaClass.getMetaMethod( "asType", [Class] as Class[] )
// Then write our own
Integer.metaClass.asType = { Class c ->
if( c == X ) {
new X( delegate )
}
else {
// if it's not an X, call the original
oldAsType.invoke( delegate, c )
}
}
3 as X
This keeps the functionality out of the Integer type, and minimizes scope of the effect (which is good or bad depending on what you're looking for).
This category will apply asType from the Integer side.
class IntegerCategory {
static Object asType(Integer inty, Class c) {
if(c == X) return new X(inty)
else return inty.asType(c)
}
}
use (IntegerCategory) {
(3 as X) instanceof X
}

Finding sub-strings in Java 6

I looked through the String API in Java 6 and I did not find any method for computing how many times a specific sub-string appears within a given String.
For example, I would like to know how many times "is" or "not" appears in the string "noisxxnotyynotxisi".
I can do the long way with a loop, but I would like to know whether there is a simpler way.
Thanks.
Edit: I'm using Java 6.
org.apache.commons.lang.StringUtils.countMatches method could be preferred.
Without using an external library, you can use String.indexOf(String str, int fromIndex); in a loop.
Update This example fully works.
/**
* #author The Elite Gentleman
* #since 31 March 2011
*
*/
public class Test {
private static final String STR = "noisxxnotyynotxisi";
public static int count(String str) {
int count = 0;
int index = -1;
//if (STR.lastIndexOf(str) == -1) {
// return count;
//}
while ((index = STR.indexOf(str, index + 1)) != -1) {
count++;
}
return count;
}
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(Test.count("is"));
System.out.println(Test.count("no"));
}
}
You can do this, but a loop would be faster.
String text = "noisxxnotyynotxisinono";
String search = "no";
int count = text.split(search,-1).length-1;
System.out.println(Arrays.toString(text.split(search,-1)));
System.out.println("count= " + count);
prints
[, isxx, tyy, txisi, , ]
count= 5
As you can see this is correct if the text starts or ends with the search value. The -1 argument stops it removing trailing seperators.
You can use a loop with indexOf() which is more efficient, but not as simple.
BTW: Java 5.0 has been EOL since Aug 2007. Perhaps its is time to look at Java 6. (though the docs are very similar)

C# 4.0 optional out/ref arguments

Does C# 4.0 allow optional out or ref arguments?
No.
A workaround is to overload with another method that doesn't have out / ref parameters, and which just calls your current method.
public bool SomeMethod(out string input)
{
...
}
// new overload
public bool SomeMethod()
{
string temp;
return SomeMethod(out temp);
}
If you have C# 7.0, you can simplify:
// new overload
public bool SomeMethod()
{
return SomeMethod(out _); // declare out as an inline discard variable
}
(Thanks #Oskar / #Reiner for pointing this out.)
As already mentioned, this is simply not allowed and I think it makes a very good sense.
However, to add some more details, here is a quote from the C# 4.0 Specification, section 21.1:
Formal parameters of constructors, methods, indexers and delegate types can be declared optional:
fixed-parameter:
attributesopt parameter-modifieropt type identifier default-argumentopt
default-argument:
= expression
A fixed-parameter with a default-argument is an optional parameter, whereas a fixed-parameter without a default-argument is a required parameter.
A required parameter cannot appear after an optional parameter in a formal-parameter-list.
A ref or out parameter cannot have a default-argument.
No, but another great alternative is having the method use a generic template class for optional parameters as follows:
public class OptionalOut<Type>
{
public Type Result { get; set; }
}
Then you can use it as follows:
public string foo(string value, OptionalOut<int> outResult = null)
{
// .. do something
if (outResult != null) {
outResult.Result = 100;
}
return value;
}
public void bar ()
{
string str = "bar";
string result;
OptionalOut<int> optional = new OptionalOut<int> ();
// example: call without the optional out parameter
result = foo (str);
Console.WriteLine ("Output was {0} with no optional value used", result);
// example: call it with optional parameter
result = foo (str, optional);
Console.WriteLine ("Output was {0} with optional value of {1}", result, optional.Result);
// example: call it with named optional parameter
foo (str, outResult: optional);
Console.WriteLine ("Output was {0} with optional value of {1}", result, optional.Result);
}
There actually is a way to do this that is allowed by C#. This gets back to C++, and rather violates the nice Object-Oriented structure of C#.
USE THIS METHOD WITH CAUTION!
Here's the way you declare and write your function with an optional parameter:
unsafe public void OptionalOutParameter(int* pOutParam = null)
{
int lInteger = 5;
// If the parameter is NULL, the caller doesn't care about this value.
if (pOutParam != null)
{
// If it isn't null, the caller has provided the address of an integer.
*pOutParam = lInteger; // Dereference the pointer and assign the return value.
}
}
Then call the function like this:
unsafe { OptionalOutParameter(); } // does nothing
int MyInteger = 0;
unsafe { OptionalOutParameter(&MyInteger); } // pass in the address of MyInteger.
In order to get this to compile, you will need to enable unsafe code in the project options. This is a really hacky solution that usually shouldn't be used, but if you for some strange, arcane, mysterious, management-inspired decision, REALLY need an optional out parameter in C#, then this will allow you to do just that.
ICYMI: Included on the new features for C# 7.0 enumerated here, "discards" is now allowed as out parameters in the form of a _, to let you ignore out parameters you don’t care about:
p.GetCoordinates(out var x, out _); // I only care about x
P.S. if you're also confused with the part "out var x", read the new feature about "Out Variables" on the link as well.
No, but you can use a delegate (e.g. Action) as an alternative.
Inspired in part by Robin R's answer when facing a situation where I thought I wanted an optional out parameter, I instead used an Action delegate. I've borrowed his example code to modify for use of Action<int> in order to show the differences and similarities:
public string foo(string value, Action<int> outResult = null)
{
// .. do something
outResult?.Invoke(100);
return value;
}
public void bar ()
{
string str = "bar";
string result;
int optional = 0;
// example: call without the optional out parameter
result = foo (str);
Console.WriteLine ("Output was {0} with no optional value used", result);
// example: call it with optional parameter
result = foo (str, x => optional = x);
Console.WriteLine ("Output was {0} with optional value of {1}", result, optional);
// example: call it with named optional parameter
foo (str, outResult: x => optional = x);
Console.WriteLine ("Output was {0} with optional value of {1}", result, optional);
}
This has the advantage that the optional variable appears in the source as a normal int (the compiler wraps it in a closure class, rather than us wrapping it explicitly in a user-defined class).
The variable needs explicit initialisation because the compiler cannot assume that the Action will be called before the function call exits.
It's not suitable for all use cases, but worked well for my real use case (a function that provides data for a unit test, and where a new unit test needed access to some internal state not present in the return value).
Use an overloaded method without the out parameter to call the one with the out parameter for C# 6.0 and lower. I'm not sure why a C# 7.0 for .NET Core is even the correct answer for this thread when it was specifically asked if C# 4.0 can have an optional out parameter. The answer is NO!
For simple types you can do this using unsafe code, though it's not idiomatic nor recommended. Like so:
// unsafe since remainder can point anywhere
// and we can do arbitrary pointer manipulation
public unsafe int Divide( int x, int y, int* remainder = null ) {
if( null != remainder ) *remainder = x % y;
return x / y;
}
That said, there's no theoretical reason C# couldn't eventually allow something like the above with safe code, such as this below:
// safe because remainder must point to a valid int or to nothing
// and we cannot do arbitrary pointer manipulation
public int Divide( int x, int y, out? int remainder = null ) {
if( null != remainder ) *remainder = x % y;
return x / y;
}
Things could get interesting though:
// remainder is an optional output parameter
// (to a nullable reference type)
public int Divide( int x, int y, out? object? remainder = null ) {
if( null != remainder ) *remainder = 0 != y ? x % y : null;
return x / y;
}
The direct question has been answered in other well-upvoted answers, but sometimes it pays to consider other approaches based on what you're trying to achieve.
If you're wanting an optional parameter to allow the caller to possibly request extra data from your method on which to base some decision, an alternative design is to move that decision logic into your method and allow the caller to optionally pass a value for that decision criteria in. For example, here is a method which determines the compass point of a vector, in which we might want to pass back the magnitude of the vector so that the caller can potentially decide if some minimum threshold should be reached before the compass-point judgement is far enough away from the origin and therefore unequivocally valid:
public enum Quadrant {
North,
East,
South,
West
}
// INVALID CODE WITH MADE-UP USAGE PATTERN OF "OPTIONAL" OUT PARAMETER
public Quadrant GetJoystickQuadrant([optional] out magnitude)
{
Vector2 pos = GetJoystickPositionXY();
float azimuth = Mathf.Atan2(pos.y, pos.x) * 180.0f / Mathf.PI;
Quadrant q;
if (azimuth > -45.0f && azimuth <= 45.0f) q = Quadrant.East;
else if (azimuth > 45.0f && azimuth <= 135.0f) q = Quadrant.North;
else if (azimuth > -135.0f && azimuth <= -45.0f) q = Quadrant.South;
else q = Quadrant.West;
if ([optonal.isPresent(magnitude)]) magnitude = pos.Length();
return q;
}
In this case we could move that "minimum magnitude" logic into the method and end-up with a much cleaner implementation, especially because calculating the magnitude involves a square-root so is computationally inefficient if all we want to do is a comparison of magnitudes, since we can do that with squared values:
public enum Quadrant {
None, // Too close to origin to judge.
North,
East,
South,
West
}
public Quadrant GetJoystickQuadrant(float minimumMagnitude = 0.33f)
{
Vector2 pos = GetJoystickPosition();
if (minimumMagnitude > 0.0f && pos.LengthSquared() < minimumMagnitude * minimumMagnitude)
{
return Quadrant.None;
}
float azimuth = Mathf.Atan2(pos.y, pos.x) * 180.0f / Mathf.PI;
if (azimuth > -45.0f && azimuth <= 45.0f) return Quadrant.East;
else if (azimuth > 45.0f && azimuth <= 135.0f) return Quadrant.North;
else if (azimuth > -135.0f && azimuth <= -45.0f) return Quadrant.South;
return Quadrant.West;
}
Of course, that might not always be viable. Since other answers mention C# 7.0, if instead what you're really doing is returning two values and allowing the caller to optionally ignore one, idiomatic C# would be to return a tuple of the two values, and use C# 7.0's Tuples with positional initializers and the _ "discard" parameter:
public (Quadrant, float) GetJoystickQuadrantAndMagnitude()
{
Vector2 pos = GetJoystickPositionXY();
float azimuth = Mathf.Atan2(pos.y, pos.x) * 180.0f / Mathf.PI;
Quadrant q;
if (azimuth > -45.0f && azimuth <= 45.0f) q = Quadrant.East;
else if (azimuth > 45.0f && azimuth <= 135.0f) q = Quadrant.North;
else if (azimuth > -135.0f && azimuth <= -45.0f) q = Quadrant.South;
else q = Quadrant.West;
return (q, pos.Length());
}
(Quadrant q, _) = GetJoystickQuadrantAndMagnitude();
if (q == Quadrant.South)
{
// Do something.
}
What about like this?
public bool OptionalOutParamMethod([Optional] ref string pOutParam)
{
return true;
}
You still have to pass a value to the parameter from C# but it is an optional ref param.
void foo(ref int? n)
{
return null;
}

Resources