Round outcome Fraction Apache Math Common - apache

Is it possible to round the fraction, e.g., 3/2 becomes 1+1/2 and 11/2 becomes 5+1/2 that is produced using Apache Common Math?
Attempt
Fraction f = new Fraction(3, 2);
System.out.println(f.abs());
FractionFormat format = new FractionFormat();
String s = format.format(f);
System.out.println(s);
results in:
3 / 2
3 / 2

It looks like what you are looking for is a Mixed Number.
Since I don't think Apache Fractions has this built in, you can use the following custom formatter:
public static String formatAsMixedNumber(Fraction frac) {
int sign = Integer.signum(frac.getNumerator())
* Integer.signum(frac.getDenominator());
frac = frac.abs();
int wholePart = frac.intValue();
Fraction fracPart = frac.subtract(new Fraction(wholePart));
return (sign == -1 ? "-" : "")
+ wholePart
+ (fracPart.equals(Fraction.ZERO) ? ("") : ("+" + fracPart));
}

Related

Error by double to string and back in bukit 1.13

i want to let the player in bukkit minecraft 1.13 solve a equation for x,
i wrote a generator and its working fine. But there are fractions possible as answers so i thought i could get the players answer, check if its a fraction, convert it to a double, back to a string and see if the fraction in decimal equals the solution:
if(cmd.getName().equalsIgnoreCase("math")) {
Player p = (Player) sender;
if(mathPlayer.contains(p.getName())) {
String eing = args[0];
String eing2 = "";
String eingf = "";
double vergl = 0.0;
if(eing.contains("/")) {
eing2 = eing.replace(",", ".");
vergl = Double.parseDouble(eing2);
eingf = Double.toString(vergl).replace(".", ",");
} else {
eingf = eing;
}
int in = mathPlayer.indexOf(p.getName());
String ergeb = mathAnswer.get(in);
if(ergeb.contains(eingf)) {
World w = p.getWorld();
w.playSound(p.getLocation(), Sound.ENTITY_EXPERIENCE_ORB_PICKUP, 10, 1);
p.sendMessage("§8[§cMATH§8] §aCongratulations!");
} else {
p.sendMessage("§8[§cMATH§8] §7Wrong: Solution: " + ergeb);
}
mathPlayer.remove(in);
mathAnswer.remove(in);
} else {
String equation = genequation(p);
sender.sendMessage("§8[§cMATH§8] §7Solve for x: §a" + equation);
p.sendMessage("§8[§cMATH§8] §7Enter answer with /math <answer>!");
}
return false;
Thanks in advance
Looking through your code i believe that you have asked the user to enter a fraction and not a decimal. However, a fraction needs to be converted to decimal before you can check it.
Easiest way to do this I believe would be like so:
double partA = Double.parseDouble(args[0].substring(0, args[0].indexOf("/")));
double partB = Double.parseDouble(args[0].substring(args[0].indexOf("/") + 1))
double answer = partA / partB
This is approximate and typed on an ipad but them you would compare it to the answer of the question.
Also, but confused as why you return false at the end instead of true.
Edit:
Use ChatColor.COLOR_CHAR for the color symbol as that could cause issues later down the line

Can an integer in Kotlin be equal to an math expression?

I am making a program that solves a math expression, for example, 2+2. Can I set an integer equal to something like this:
val input = "2+2"
input.toInt()
Kotlin doesn't have any built in ways for evaluating arbitrary expressions. The toInt function can only parse a String containing a single whole number (it's just a wrapper for Integer.parseInt).
If you need this functionality, you'll have to parse and evaluate the expression yourself. This problem is no different than having to do it in Java, for which you can find discussion and multiple solutions (including hacks, code samples, and libraries) here.
No you cannot convert directly a String Mathematical Expression to Integer.
But you can try following approach to convert String Mathematical Expression to Integer ->>
var exp: String = "2+3-1*6/4"
var num: String = ""
var symbol: Char = '+'
var result: Int = 0
for(i in exp)
{
if(i in '0'..'9')
num += i
else
{
if(symbol == '+')
result += Integer.parseInt(num)
else if(symbol == '-')
result -= Integer.parseInt(num)
else if(symbol == '*')
result *= Integer.parseInt(num)
else if(symbol == '/')
result /= Integer.parseInt(num)
num=""
symbol = i
}
}
//To calculate the divide by 4 ( result/4 ) in this case
if(symbol == '+')
result += Integer.parseInt(num)
else if(symbol == '-')
result -= Integer.parseInt(num)
else if(symbol == '*')
result *= Integer.parseInt(num)
else if(symbol == '/')
result /= Integer.parseInt(num)
println("result is $result") //Output=> result is 6
}
No you can't.
You can like this:
val a = "2"
val b = "2"
val c = a.toInt() + b.toInt()
Or
val input = "2+2"
val s = input.split("+")
val result = s[0].toInt() + s[1].toInt()
This can be done with the kotlin script engine. For details see Dynamically evaluating templated Strings in Kotlin
But in a nutshell it's like this:
val engine = ScriptEngineManager().getEngineByExtension("kts")!!
engine.eval("val x = 3")
val res = engine.eval("x + 2")
Assert.assertEquals(5, res)
No, Integer cannot be equal to math expression.
You may use String Templates
Strings may contain template expressions, i.e. pieces of code that are evaluated and whose results are concatenated into the
string.
A template expression starts with a dollar sign ($) and consists of either a simple name:
val i = 10
val s = "i = $i" // evaluates to "i = 10"

Generate a random double between 1 and max in c++/cli

How would i generate a random double between 1 and a defined max in c++/cli, ive use random_number_distribution and mersenne twister in the random header before but never in cli, will this work in cli with random or system::random, or are there any similar alternatives? Thanks.
Here's how
double randDouble(double fMin, double fMax)
{
double f = (double)rand() / RAND_MAX;
return fMin + f * (fMax - fMin);
}
The System::Random class, with its NextDouble method is what you want. NextDouble will return a double >= 0.0 and < 1.0. So, to return a value between 1 and a max:
double RandOneToMax(double max)
{
Random^ r = ...;
return (r->NextDouble() * (max - 1)) + 1;
}

Convert numbers in Chinese characters to arabic numbers

I am a newbie in programming and i start with Objective C as my first language.
I am messing around with some books and tutorials, at last programing a calculator...
Everything fine and i am getting into (programming makes really fun)
Now i am asking myself how I could translate arabic numbers to chinese numbers
(e.g. arabic 4 is in chinese 四 and 8 is 八 which means 四 + 四 = 八
The chinese number system is kind of different than arabic they have signs for 100, 1000, 10000 and ja kind of twisted, which screws up my brain ... anyway do anybody have some advice, hints, tips or solutions how i can tell the computer how to work with this numbers, or even how to calculate with them?
I think everything is possible so i wont ask "If its even possible?"
Considering the Chinese numerical system (Mandarin) as described by wikipedia http://en.wikipedia.org/wiki/Chinese_numerals, where for instance:
45 is interpreted as [4] [10] [5] and written 四十五
114 is interpreted as [1] [100] [1] [10] [4] and written 一百一十四
So the trick is to decompose a number as powers of 10:
x = c(k)*10^k + ... + c(1)*10 + c(0)
where k is the largest power of 10 that divides x such that the quotient is at least 1. In the 2nd example above, 114 = 1*10^2 + 1*10 + 4.
This x = c(k)*10^k + ... + c(1)*10 + c(0) becomes [c(k)][10^k]...[c(1)][10][c(0)]. In the 2nd example again, 114 = [1] [100] [1] [10] [4].
Then map each number within bracket to the corresponding sinogram:
0 = 〇
1 = 一
2 = 二
3 = 三
4 = 四
5 = 五
6 = 六
7 = 七
8 = 八
9 = 九
10 = 十
100 = 百
1000 = 千
10000 = 万
As long as you keep track of the [c(k)][10^k]...[c(1)][10][c(0)] form, it's easy to convert to an integer that the computer can handle or to the corresponding Chinese numeral. So it's this [c(k)][10^k]...[c(1)][10][c(0)] form that I'd store in an integer array of size k+2.
I'm not familiar with Objective-C, thus I can't help you with a solution for iOS.
Nonetheless, following is the Java code for Android...
I assumed it might help you, as well as it helped me.
double text2double(String text) {
String[] units = new String[] { "〇", "一", "二", "三", "四",
"五", "六", "七", "八", "九"};
String[] scales = new String[] { "十", "百", "千", "万",
"亿" };
HashMap<String, ScaleIncrementPair> numWord = new HashMap<String, ScaleIncrementPair>();
for (int i = 0; i < units.length; i++) {
numWord.put(units[i], new ScaleIncrementPair(1, i));
}
numWord.put("零", new ScaleIncrementPair(1, 0));
numWord.put("两", new ScaleIncrementPair(1, 2));
for (int i = 0; i < scales.length; i++) {
numWord.put(scales[i], new ScaleIncrementPair(Math.pow(10, (i + 1)), 0));
}
double current = 0;
double result = 0;
for (char character : text.toCharArray()) {
ScaleIncrementPair scaleIncrement = numWord.get(String.valueOf(character));
current = current * scaleIncrement.scale + scaleIncrement.increment;
if (scaleIncrement.scale > 10) {
result += current;
current = 0;
}
}
return result + current;
}
class ScaleIncrementPair {
public double scale;
public int increment;
public ScaleIncrementPair(double s, int i) {
scale = s;
increment = i;
}
}
You can make use of NSNumberFormatter.
Like below code, firstly get NSNumber from chinese characters, then combine them.
func getNumber(fromText text: String) -> NSNumber? {
let locale = Locale(identifier: "zh_Hans_CN")
let numberFormatter = NumberFormatter()
numberFormatter.locale = locale
numberFormatter.numberStyle = .spellOut
guard let number = numberFormatter.number(from: text) else { return nil }
print(number)
return number
}

Getting a values most significant digit in Objective C

I currently have code in objective C that can pull out an integer's most significant digit value. My only question is if there is a better way to do it than with how I have provided below. It gets the job done, but it just feels like a cheap hack.
What the code does is that it takes a number passed in and loops through until that number has been successfully divided to a certain value. The reason I am doing this is for an educational app that splits a number up by it's value and shows the values added all together to produce the final output (1234 = 1000 + 200 + 30 + 4).
int test = 1;
int result = 0;
int value = 0;
do {
value = input / test;
result = test;
test = [[NSString stringWithFormat:#"%d0",test] intValue];
} while (value >= 10);
Any advice is always greatly appreciated.
Will this do the trick?
int sigDigit(int input)
{
int digits = (int) log10(input);
return input / pow(10, digits);
}
Basically it does the following:
Finds out the number of digits in input (log10(input)) and storing it in 'digits'.
divides input by 10 ^ digits.
You should now have the most significant number in digits.
EDIT: in case you need a function that get the integer value at a specific index, check this function out:
int digitAtIndex(int input, int index)
{
int trimmedLower = input / (pow(10, index)); // trim the lower half of the input
int trimmedUpper = trimmedLower % 10; // trim the upper half of the input
return trimmedUpper;
}