Valid math expressions:
a * b + c
-a * b / 1.50
a + b * 4.6 - k
And these are invalid math expressions:
--a *+ b # 1.5.0 // two consecutive signs, two consecutive operators, invalid operator, invalid number
I am not looking for valid parentheses, only the combination of float/double digits and variables.
I tried to come up something like this - but its not working
^[-+]?([-+/]\d+(.\d+)? || [-+/][a-zA-Z])*
Any help would be appreciated. TIA
Related
It appears that the logical NOT operator ! has non-intuitive order of operations in arithemtic:
set.seed(42)
a <- sample(100, 3)
b <- sample(100, 3)
c <- sample(100, 3)
l <- (1:3) <= 2
a * !l - b * !l + c
# 0 0 29
# same expression, but with parentheses for explicit grouping order of operations
(a * !l) - (b * !l) + c
# 74 14 43
There must be something I do not understand about the ! operator in relation to * or conversion from logical to numeric?
Note that in R, the negation operator ! will apply to entire expression to the right of the operator until it gets to the end or encounters an expression with a lower precedence. It does not just negate the most immediate term. Recall also that 0 is treated as FALSE and any other number is TRUE. So observe
!0
# [1] TRUE
!5
# [1] FALSE
!5-5
# [1] TRUE
!5-3-2
# [1] TRUE
(!5)-3-2
# [1] -5
So you see in the case of !5-3-2 the negation isn't happening until after the 5-3-2 is evaluated. Without the parenthesis, the negation is the very last thing that happens.
So when you write
a * !l - b * !l + c
that's the same as
a * !(l - (b * !(l + c)))
Because all the operations have to happen to the right of the negation before the negation can occur.
If you want to negate just the l terms, you can do
a * (!l) - b * (!l) + c
This is a function of the operator precedence in R (see the ?Syntax help page for details). It's once of the last operators to be evaluated in the given expression.
Note that & and | have a lower precedence than ! so when you do
!a | !b & !c
that's the same as
(!a) | ((!b) & (!c))
so this roughly would be what you expect if you just stick to logical operators. It just gets a bit odd perhaps when you combine logical and arithmetic operators.
(%i2) x : expand(cosh(1)*sqrt(3+5*t));
(%o2) cosh(1) sqrt(5 t + 3)
(%i3) expand(float(x));
0.5
(%o3) 1.543080634815244 (5.0 t + 3.0)
How can I get Maxima to incorporate the prefactor into the radical? I'm looking for something that in this case yields something like
0.5
(%o3) (11.90548922 t + 7.143293537)
For numbers as small as these this is not a big deal, but for numerical evaluations Maxima tends to substitute rational approximations that may involve very large denominators, so that I end up with expressions where the prefactor is a very small number (like 6.35324353 × 10-23) and the numbers inside the square root are very large numbers (like 5212548545863256475196584785455844385452665612552468), so that it isn't obvious even what the order of magnitude of the result is.
Here's a solution which uses pattern matching.
(%i1) matchdeclare (cc, numberp, [bb, aa], all) $
(%i2) defrule (r1f, cc*bb^0.5, foof(cc,bb));
0.5
(%o2) r1f : bb cc -> foof(cc, bb)
(%i3) defrule (r2f, aa*cc*bb^0.5, aa*foof(cc,bb));
0.5
(%o3) r2f : aa bb cc -> aa foof(cc, bb)
(%i4) foof(a,b):= (expand(a^2*b))^0.5 $
(%i5) apply1 (1.543080634815244*(5.0*t + 3.0)^0.5, r1f, r2f);
0.5
(%o5) (11.90548922770908 t + 7.143293536625449)
(%i6) apply1 (1.543080634815244*x*y*(5.0*t + 3.0)^0.5, r1f, r2f);
0.5
(%o6) (11.90548922770908 t + 7.143293536625449) x y
(%i7) apply1 (1/(1 + 345.43*(2.23e-2*u + 8.3e-4)^0.5), r1f, r2f);
1
(%o7) --------------------------------------------
0.5
(2660.87803327 u + 99.03716446700001) + 1
It took some experimentation to figure out suitable rules r1f and r2f. Note that these rules match ...^0.5 but not sqrt(...) (i.e. exponent = 1/2 instead of 0.5). Of course if you want to match sqrt(...) you can create additional rules for that.
Not guaranteed to work for you -- a rule might match too much or too little. It's worth a try, anyway.
I need to write my own recursive function in ML that somehow uses ord to convert a string of numbers to integer type. I can use helper functions, but apparently I should be able to do this without using one (according to my professor).
I can assume that the input is valid, and is a positive integer (in string type of course).
So, the call str2int ("1234") should output 1234: int
I assume I will need to use explode and implode at some point since ord operates on characters, and my input is a string. Any direction would be greatly appreciated.
Given that you asked, I guess I can ruin all the fun for you. This will solve your problem, but ironically, it won't help you.
Well, the ordinal number for the character #'0' is 48. So, this means that if you subtract of any ordinal representing a digit the number 48 you get its decimal value. For instance
ord(#"9") - 48
Yields 9.
So, a function that takes a given character representing a number from 0-9 and turns it into the corresponding decimal is:
fun charToInt(c) = ord(c) - 48
Supposing you had a string of numbers like "2014". Then you can first explode the string into list of characters and then map every character to its corresponding decimal.
For instance
val num = "2014"
val digits = map charToInt (explode num)
The explode function is a helper function that takes a string and turn it into a list of characters.
And now digits would be a list of integers representing the decimal numbers [2,0,1,4];
Then, all you need is to apply powers of 10 to obtain the final integer.
2 * 10 ^ 3 = 2000
0 * 10 ^ 2 = 0
1 * 10 ^ 1 = 10
4 * 10 ^ 0 = 4
The result would be 2000 + 0 + 10 + 4 = 2014
You could define a helper function charsToInt that processes the digits in the string from left to right.
At each step it converts the leftmost digit c into a number and does addition with the 10x-multiple of n (which is the intermediary sum of all previously parsed digits) ...
fun charsToInt ([], n) = n
| charsToInt (c :: cs, n) = charsToInt (cs, 10*n + ord c - 48)
val n = charsToInt (explode "1024", 0)
Gives you: val n = 1024 : int
As you see the trick is to pass the intermediary result down to the next step at each recursive call. This is a very common technique when dealing with these kind of problems.
Here's what I came up with:
fun pow10 n =
if n = 0 then 1 else 10*pow10(n-1);
fun str2help (L,n) =
if null L then 0
else (ord(hd L)-48) * pow10(n) + str2help(tl L, n-1);
fun str2int (string) =
str2help(explode string, size string -1);
str2int ("1234");
This gives me the correct result, though is clearly not the easiest way to get there.
I am trying to make a function to round a floating point number to a defined length of digits. What I have come up with so far is this:
import Numeric;
digs :: Integral x => x -> [x] <br>
digs 0 = [] <br>
digs x = digs (x `div` 10) ++ [x `mod` 10]
roundTo x t = let d = length $ digs $ round x <br>
roundToMachine x t = (fromInteger $ round $ x * 10^^t) * 10^^(-t)
in roundToMachine x (t - d)
I am using the digs function to determine the number of digits before the comma to optimize the input value (i.e. move everything past the comma, so 1.234 becomes 0.1234 * 10^1)
The roundTo function seems to work for most input, however for some inputs I get strange results, e.g. roundTo 1.0014 4 produces 1.0010000000000001 instead of 1.001.
The problem in this example is caused by calculating 1001 * 1.0e-3 (which returns 1.0010000000000001)
Is this simply a problem in the number representation of Haskell I have to live with or is there a better way to round a floating point number to a specific length of digits?
I realise this question was posted almost 2 years back, but I thought I'd have a go at an answer that didn't require a string conversion.
-- x : number you want rounded, n : number of decimal places you want...
truncate' :: Double -> Int -> Double
truncate' x n = (fromIntegral (floor (x * t))) / t
where t = 10^n
-- How to answer your problem...
λ truncate' 1.0014 3
1.001
-- 2 digits of a recurring decimal please...
λ truncate' (1/3) 2
0.33
-- How about 6 digits of pi?
λ truncate' pi 6
3.141592
I've not tested it thoroughly, so if you find numbers this doesn't work for let me know!
This isn't a haskell problem as much as a floating point problem. Since each floating point number is implemented in a finite number of bits, there exist numbers that can't be represented completely accurately. You can also see this by calculating 0.1 + 0.2, which awkwardly returns 0.30000000000000004 instead of 0.3. This has to do with how floating point numbers are implemented for your language and hardware architecture.
The solution is to continue using your roundTo function for doing computation (it's as accurate as you'll get without special libraries), but if you want to print it to the screen then you should use string formatting such as the Text.Printf.printf function. You can specify the number of digits to round to when converting to a string with something like
import Text.Printf
roundToStr :: (PrintfArg a, Floating a) => Int -> a -> String
roundToStr n f = printf ("%0." ++ show n ++ "f") f
But as I mentioned, this will return a string rather than a number.
EDIT:
A better way might be
roundToStr :: (PrintfArg a, Floating a) => Int -> a -> String
roundToStr n f = printf (printf "%%0.%df" n) f
but I haven't benchmarked to see which is actually faster. Both will work exactly the same though.
EDIT 2:
As #augustss has pointed out, you can do it even easier with just
roundToStr :: (PrintfArg a, Floating a) => Int -> a -> String
roundToStr = printf "%0.*f"
which uses a formatting rule that I was previously unaware of.
I also think that avoiding string conversion is the way to go; however, I would modify the previous post (from schanq) to use round instead of floor:
round' :: Double -> Integer -> Double
round' num sg = (fromIntegral . round $ num * f) / f
where f = 10^sg
> round' 4 3.99999
4.0
> round' 4 4.00001
4.0
According to wiki shifts can be used to calculate powers of 2:
A left arithmetic shift by n is
equivalent to multiplying by 2^n
(provided the value does not
overflow), while a right arithmetic
shift by n of a two's complement value
is equivalent to dividing by 2^n and
rounding toward negative infinity.
I was always wondering if any other bitwise operators (~,|,&,^) make any mathematical sense when applied to base-10? I understand how they work, but do results of such operations can be used to calculate anything useful in decimal world?
"yep base-10 is what I mean"
In that case, yes, they can be extended to base-10 in several ways, though they aren't nearly as useful as in binary.
One idea is that &, |, etc. are the same as doing arithmetic mod-2 to the individual binary digits. If a and b are single binary-digits, then
a & b = a * b (mod 2)
a ^ b = a + b (mod 2)
~a = 1-a (mod 2)
a | b = ~(~a & ~b) = 1 - (1-a)*(1-b) (mod 2)
The equivalents in base-10 would be (note again these are applied per-digit, not to the whole number)
a & b = a * b (mod 10)
a ^ b = a + b (mod 10)
~a = 9-a (mod 10)
a | b = ~(~a & ~b) = 9 - (9-a)*(9-b) (mod 10)
The first three are useful when designing circuits which use BCD (~a being the 9's complement), such as non-graphing calculators, though we just use * and + rather than & and ^ when writing the equations. The first is also apparently used in some old ciphers.
A fun trick to swap two integers without a temporary variable is by using bitwise XOR:
void swap(int &a, int &b) {
a = a ^ b;
b = b ^ a; //b now = a
a = a ^ b; //knocks out the original a
}
This works because XOR is a commutative so a ^ b ^ b = a.
Yes, there are other useful operations, but they tend to be oriented towards operations involving powers of 2 (for obvious reasons), e.g. test for odd/even, test for power of 2, round up/down to nearest power of 2, etc.
See Hacker's Delight by Henry S. Warren.
In every language I've used (admittedly, almost exclusively C and C-derivatives), the bitwise operators are exclusively integer operations (unless, of course, you override the operation).
While you can twiddle the bits of a decimal number (they have their own bits, after all), it's not necessarily going to get you the same result as twiddling the bits of an integer number. See Single Precision and Double Precision for descriptions of the bits in decimal numbers. See Fast Inverse Square Root for an example of advantageous usage of bit twiddling decimal numbers.
EDIT
For integral numbers, bitwise operations always make sense. The bitwise operations are designed for the integral numbers.
n << 1 == n * 2
n << 2 == n * 4
n << 3 == n * 8
n >> 1 == n / 2
n >> 2 == n / 4
n >> 3 == n / 8
n & 1 == {0, 1} // Set containing 0 and 1
n & 2 == {0, 2} // Set containing 0 and 2
n & 3 == {0, 1, 2, 3} // Set containing 0, 1, 2, and 3
n | 1 == {1, n, n+1}
n | 2 == {2, n, n+2}
n | 3 == {3, n, n+1, n+2, n+3}
And so on.
You can calculate logarithms using just bitwise operators...
Finding the exponent of n = 2**x using bitwise operations [logarithm in base 2 of n]
You can sometime substitute bitwise operations for boolean operations. For example, the following code:
if ((a < 0) && (b < 0)
{
do something
{
In C this can be replaced by:
if ((a & b) < 0)
{
do something
{
This works because one bit in an integer is used as the sign bit (1 indicates negative). The and operation (a & b) will be a meaningless number, but its sign will be the bitwise and of the signs of the numbers and hence checking the sign of the result will work.
This may or may not benefit performance. Doing two boolean tests/branches will be worse on a number of architectures and compilers. Modern x86 compilers can probably generate a single branch using a some of the newer instruction even with the normal syntax.
As always, if it does result in a performance increase... Comment the code - i.e. put the "normal" way of doing it in a comment and say it's equivalent but faster.
Likewise, ~ | and ^ can be used in a similar way it all the conditions are (x<0).
For comparison conditions you can generally use subtraction:
if ((a < b) | (b < c))
{
}
becomes:
if (((a-b) | (b-c)) < 0)
{
}
because a-b will be negative only if a is less than b. There can be issues with this one if you get within a factor of 2 of max int - i.e. arithmetic overflow, so be careful.
These are valid optimizations in some cases, but otherwise quite useless. And to get really ugly, floating point numbers also have sign bits... ;-)
EXAMPLE:
As an example, lets say you want to take action depending on the order of a,b,c. You can do some nested if/else constructs, or you can do this:
x = ((a < b) << 2) | ((b < c) << 1) | (c < a);
switch (x):
I have used this in code with up to 9 conditions and also using the subtractions mentioned above with extra logic to isolate the sign bits instead of less-than. It's faster than the branching equivalent. However, you no longer need to do subtraction and sign bit extraction because the standard was updated long ago to specify true as 1, and with conditional moves and such, the actual less-than can be quite efficient these days.