How to turn a string into a floating point number in ATS? - ats

Basically, I am looking for a function of the following type:
fun string2double(rep: string): double
which converts a string representing a floating point number into the number.
For instance, string2double("3.14") should return 3.14.

It can be implemented as follows:
fun string2double(x: string): double = g0string2float_double(x)

Related

Integers converted to strings do not work as expected

Issue comparing str() to what I'd expect is their String form
Code :
int i = 2;
String r = str(i);
println(r);
if (r == "2") {
println("String works");
} else println("String doesnt work");
if (i == 2) {
println("Integer works");
} else println("Integer doesnt work");
Prints :
2
String doesnt work
Integer works
The second if statement is a copy paste of the first, with only the variable and value changed so theres nothing wrong with my if statement
Processing documentation states (about str()):
Converts a value of a primitive data type (boolean, byte, char, int, or float) to its String
representation. For example, converting an integer with str(3) will return the String value of "3",
converting a float with str(-12.6) will return "-12.6", and converting a boolean with str(true) will
return "true".
Also doesnt work with str(2) == "2" or str(i) == "2"
How do I fix this and get it to work (without converting it back to an integer because that would make my code a bit ugly)
You should not compare String values using ==. Use the equals() function instead:
if (r.equals("2")) {
From the reference:
To compare the contents of two Strings, use the equals() method, as in if (a.equals(b)), instead of if (a == b). A String is an Object, so comparing them with the == operator only compares whether both Strings are stored in the same memory location. Using the equals() method will ensure that the actual contents are compared. (The troubleshooting reference has a longer explanation.)
More info here: How do I compare strings in Java?

How can I see the actual binary content of a VB6 Double variable?

I have hunted about quite a bit but can't find a way to get at the Hexadecimal or Binary representation of the content of a Double variable in VB6. (Are Double variables held in IEEE754 format?)
The provided Hex(x) function is no good because it integerizes its input first.
So if I want to see the exact bit pattern produced by Atn(1), Hex(Atn(1)) does NOT produce it.
I'm trying to build a mathematical function containing If clauses. I want to be able to see that the values returned on either side of these boundaries are, as closely as possible, in line.
Any suggestions?
Yes, VB6 uses standard IEEE format for Double. One way to get what you want without resorting to memcpy() tricks is to use two UDTs. The first would contain one Double, the second a static array of 8 Byte. LSet the one containing the Double into the one containing the Byte array. Then you can examine each Byte from the Double one by one.
If you need to see code let us know.
[edit]
At the module level:
Private byte_result() As Byte
Private Type double_t
dbl As Double
End Type
Private Type bytes_t
byts(1 To 8) As Byte
End Type
Then:
Function DoubleToBytes (aDouble As Double) As Byte()
Dim d As double_t
Dim b As bytes_t
d.dbl = aDouble
LSet b = d
DoubleToBytes = b.byts
End Function
To use it:
Dim Indx As Long
byte_result = DoubleToBytes(12345.6789#)
For Indx = 1 To 8
Debug.Print Hex$(byte_result(Indx)),
Next
This is air code but it should give you the idea.

Inherent math operation in Java

I'm writing essentially a small calaculator where you input two numbers, an operand like "+, -, *, /" etc and it'll preform that function.
My initial thoughts have been to just have the variables get entered by the user, than just have them computed as imputed. I would like to do it this way, as to avoid writing several if else statements and keeping things a bit cleaner. But I can't find a place explaining how to inherently compute the values and imputed characters.
package hw2p1;
import java.util.Scanner;
import javax.script.*;
public class Calculator {
public static void PrintCalculator(){
Scanner input = new Scanner(System.in);
double num1; //1st entered number
double num2; //2nd entered number
String val1; //Math operator like + - * /.
double math1; //the results.
String equation = "";
System.out.print("Enter the first number:");
num1 = input.nextDouble();
System.out.print("Enter the second number:");
num2 = input.nextDouble();
System.out.print("Enter an operator:");
val1 = input.next();
I know this is incomplete, but I don't know/can't find the logic on how to string the three inputted values together and compute them.
The simplest solution would be
public static double calculate(double a, String op, double b) {
switch(op) {
case "+": return a+b;
case "-": return a-b;
case "*": return a*b;
case "/": return a/b;
case "%": return a%b;
case "^": return Math.pow(a, b);
default: throw new IllegalArgumentException("no such operator '"+op+"'");
}
}
which is semantically equivalent to a sequence of if-else statements, but clearly showing the intention and potentially more efficient, though there’s not much worth in speculating about performance here.
It can be invoked like
double math1 = calculate(num1, val1, num2); //the results.
but you really should retink your variable naming scheme. If you have to append a comment telling the purpose behind every declaration, you’re clearly doing something wrong. Why not naming the variables, e.g. firstInputNumber, secondInputNumber, operator and result in the first place? Then, you don’t need the comments telling the variable’s purposes.
I could not remove if-else but may be you can try something like this
public static void main(String[] args) {
int result = operate("+").applyAsInt(10, 20);
System.out.println(result);
}
private static IntBinaryOperator operate(String op){
switch(op){
case "+": return Math::addExact;
case "-": return Math::subtractExact;
//other cases
}
throw new RuntimeException("incorrect operator");
}
One issue though, Math do not have methods for double
tl;dr
You have to explicitly state that "+" means addition.
Long Anwser
When the user types something when your program runs, all of it is just characters. It's up to your program to interpret those characters to do something meaningful. Scanner can be helpful with this because it knows how to interpret the characters 1234 as an int. However, beyond data for the built-in types, Scanner is completely dumb.
In building your own calculator program, you are basically writing a simplified version of the Java compiler. The compiler is a program which reads characters from a file and converts them into something that can execute on a Java Virtual Machine. You will do much of the same thing in your own calculator program. This means that you have to explicitly write the rules that interpret characters that represent mathematical operators into the operations that they actually perform.
If you are interested in learning more about this topic, you can do some research on compilers and interpreters. They are generally made of two pieces: the lexical analyzer, or lexer, and the parser. This is all especially necessary if you want to allow the user to type in a complete mathematical expression like 2 + 3 rather than prompting them for each piece of the expression individually.
I hope this gives you some terminology that you can use in a Google search.

Stop Rounding with NSExpression in Calculator [duplicate]

I want to calculate a string, which I'm doing by this:
NSExpression *expression = [NSExpression expressionWithFormat:calculationString];
float result = [[expression expressionValueWithObject:nil context:nil] floatValue];
NSLog(#"%f", result);
The problem is, when calculationstring is 1/2, the result is 0. I tried to change float with double and NSNumber and the %f to %f and %#, but I always just get 0. What to I have to change?
Also if it matters, I am in Europe, so I have commas instead of points for this value, but it shouldn't matter as I am logging with %f which shows it as points. Just for information
Basically, you just need to tell it that you are performing floating point operation,
1.0/2
1.0/2.0
1/2.0
Will all work
Typing in NSExpression is much like in C: literals that look like integers (no decimal point/comma) are treated as integers and thus use integer division. (Under integer division, 1/2 is zero. If you want 0.5, you need floating point division.) This happens when the expression is parsed and evaluated, so attempting to change the type of the result or the formatting of the output has no effect -- those things happen after parsing and evaluation.
If your calculationString is entirely under your control, it's easy to make sure that you use floating point literals anywhere you want floating point division. (That is, use 1.0/2 instead of 1/2.) If not, you'll need to change it such that it does -- here it's probably better to decompose the parsed NSExpression and change an operand rather than munge the string.
Followup edit on the "decompose" bit: String munging in content that you know to have higher-order structure is generally problematic. And with NSExpression, you already have a parser (who's smarter than a simple regex) decomposing the string for you — that is in fact what NSExpression is all about.
So, if you're working with a user-provided string, don't try to change the expression by changing the string. Let NSExpression parse it, then use properties of the resulting object to pick it apart into its constituent expressions. If your string is simply "1/2", then your expression has an array of two arguments and the function "divide:by:" — you can replace it with an equivalent function where one of the arguments is explicitly a floating-point value:
extension NSExpression {
var floatifiedForDivisionIfNeeded: NSExpression {
if function == "divide:by:", let args = arguments, let last = args.last,
let firstValue = args.first?.constantValue as? NSNumber {
let newFirst = NSExpression(forConstantValue: firstValue.doubleValue)
return NSExpression(forFunction: function, arguments: [newFirst, last])
} else {
return self
}
}
}
I think You need to User DDMathParser Which is best in this situation. I have used it in One of my project which is facing same problem as you have faced
DDMathEvaluator *eval = [DDMathEvaluator defaultMathEvaluator];
id value=[eval evaluateString:#"1/2" withSubstitutions:nil error:&error];
NSLog(#"Result %#",value);
Result 0.5
Rickster's solution worked, but had problems with expressions like 5*5/2, where the first argument (here 5*5) was not just a number.
I found a different solution here that works for me: https://stackoverflow.com/a/46554342/6385925
for people who still have this problem i did a somewhat quick fix:
extension String {
var mathExpression: String {
var returnValue = ""
for value in newString.components(separatedBy: " ") {
if value.isOperator {
returnValue += value
} else {
returnValue += "\(Double(value) ?? 0)"
}
}
return returnValue
}
var isOperator: Bool {
["+", "-", "/", "x", "*"].contains(self)
}
}

what does that mean for Text.hashCode() & Interger.MAX_VALUE?

Recently, I am reading the definitive guide of hadoop.
I have two questions:
1.I saw a piece of code of one custom Partitioner:
public class KeyPartitioner extends Partitioner<TextPair, Text>{
#Override
public int getPartition(TextPair key, Text value, int numPartitions){
return (key.getFirst().hashCode()&Interger.MAX_VALUE)%numPartitions;
}
}
what does that mean for &Integer.MAX_VALUE? why should use & operator?
2.I also want write a custom Partitioner for IntWritable. So is it OK and best for key.value%numPartitions directly?
Like I already wrote in the comments, it is used to keep the resulting integer positive.
Let's use a simple example using Strings:
String h = "Hello I'm negative!";
int hashCode = h.hashCode();
hashCode is negative with the value of -1937832979.
If you would mod this with a positive number (>0) that denotes the partition, the resulting number is always negative.
System.out.println(hashCode % 5); // yields -4
Since partitions can never be negative, you need to make sure the number is positive. Here comes a simple bit twiddeling trick into play, because Integer.MAX_VALUE has all-ones execpt the sign bit (MSB in Java as it is big endian) which is only 1 on negative numbers.
So if you have a negative number with the sign bit set, you will always AND it with the zero of the Integer.MAX_VALUE which is always going to be zero.
You can make it more readable though:
return Math.abs(key.getFirst().hashCode() % numPartitions);
For example I have done that in Apache Hama's partitioner for arbitrary objects:
#Override
public int getPartition(K key, V value, int numTasks) {
return Math.abs(key.hashCode() % numTasks);
}

Resources