In Maple,
restart; with(LinearAlgebra);
E := Matrix([[A, B]]);
E. Transpose(E);
yields
A^2 + B^2
However, I would like that Maple treat A and B as block matrices and yield
A.Transpose(A) + B.Transpose(B)
Is this possible?
You'll want to use the Maple assume() command for this (link). Scroll down that link, or ctrl-f and find the part where they show how to assume that a variable is a "SquareMatrix" type. Basically, Maple is treating your variables like they are real numbers, and you need to tell it not to do that. Once you get the assume statement right, it should print out the matrix-based solution.
If you get a lot of crufty extra symbols, this might be because Maple usually flags variables for which the assume() function was used (so the user remembers they are making an assumption about that variable). For example, it often replaces a with ~a if you issue an assume() regarding a. You can turn this off with the command interface(showassumed=0).
Related
I am attempting to create a linear combination of two numbers to create their GCD. The code I have so far can find the expanded solution. I have done all of the (hard) math for it (i.e. find the GCD using Euclid's Algorithm, then work backward essentially) and it will result in something like this for example (the two starting numbers are 1215 and 960):
((960-(3*(1215-(1*960))))-(3*((1215-(1*960))-(1*(960-(3*(1215-(1*960))))))))
In my actual solution there is a space between every component (e.g. '( ( 960 - (3 * '...)
but I am trying to simplify this into the equation:
((-15*1215)+(19*960))
I feel like the best approach is to create an Expression Tree, but I don't know how to without actually just evaluating the answer.
It sounds like you are looking for a symbolic computation system. Here's one approach using Maxima (https://maxima.sourceforge.net). I'll enable stardisp to show * between terms of a product. I'll also input numbers like 960 as symbols in order to suppress arithmetic on them by writing them as \960 etc. Note that 1 and 3 are input as ordinary numbers so arithmetic is carried out on them.
(%i13) stardisp:true;
(%o13) true
(%i14) 2*3;
(%o14) 6
(%i15) \2*\3;
(%o15) 2*3
(%i16) ((\960-(3*(\1215-(1*\960))))-(3*((\1215-(1*\960))-(1*(\960-(3*(\1215-(1*\960))))))));
(%o16) 960 - 3*(1215 - 960) - 3*((- 2*960) + 3*(1215 - 960)
+ 1215)
(%i17) factor(%);
(%o17) 19*960 - 15*1215
Maybe you want to replace the numbers with symbols a, b, c, etc to get a more general solution.
There are many other symbol computation systems, a web search will find them. Good luck and have fun.
I'm trying to understand the theorem behind "call-by-need." I do understand the definition, but I'm a bit confused. I would like to see a simple example which shows how call-by-need works.
After reading some previous threads, I found out that Haskell uses this kind of evaluation. Are there any other programming languages which support this feature?
I read about the call-by-name of Scala, and I do understand that call-by-name and call-by-need are similar but different by the fact that call-by-need will keep the evaluated value. But I really would love to see a real-life example (it does not have to be in Haskell), which shows call-by-need.
The function
say_hello numbers = putStrLn "Hello!"
ignores its numbers argument. Under call-by-value semantics, even though an argument is ignored, the parameter at the function call site may need to be evaluated, perhaps because of side effects that the rest of the program depends on.
In Haskell, we might call say_hello as
say_hello [1..]
where [1..] is the infinite list of naturals. Under call-by-value semantics, the CPU would run off trying to build an infinite list and never get to the say_hello at all!
Haskell merely outputs
$ runghc cbn.hs
Hello!
For less dramatic examples, the first ten natural numbers are
ghci> take 10 [1..]
[1,2,3,4,5,6,7,8,9,10]
The first ten odds are
ghci> take 10 $ filter odd [1..]
[1,3,5,7,9,11,13,15,17,19]
Under call-by-need semantics, each value — even a conceptually infinite one as in the examples above — is evaluated only to the extent required and no more.
update: A simple example, as asked for:
ff 0 = 1
ff 1 = 1
ff n = go (ff (n-1))
where
go x = x + x
Under call-by-name, each invocation of go evaluates ff (n-1) twice, each for each appearance of x in its definition (because + is strict in both arguments, i.e. demands the values of the both of them).
Under call-by-need, go's argument is evaluated at most once. Specifically, here, x's value is found out only once, and reused for the second appearance of x in the expression x + x. If it weren't needed, x wouldn't be evaluated at all, just as with call-by-name.
Under call-by-value, go's argument is always evaluated exactly once, prior to entering the function's body, even if it isn't used anywhere in the function's body.
Here's my understanding of it, in the context of Haskell.
According to Wikipedia, "call by need is a memoized variant of call by name where, if the function argument is evaluated, that value is stored for subsequent uses."
Call by name:
take 10 . filter even $ [1..]
With one consumer the produced value disappears after being produced so it might as well be call-by-name.
Call by need:
import qualified Data.List.Ordered as O
h = 1 : map (2*) h <> map (3*) h <> map (5*) h
where
(<>) = O.union
The difference is, here the h list is reused by several consumers, at different tempos, so it is essential that the produced values are remembered. In a call-by-name language there'd be much replication of computational effort here because the computational expression for h would be substituted at each of its occurrences, causing separate calculation for each. In a call-by-need--capable language like Haskell the results of computing the elements of h are shared between each reference to h.
Another example is, most any data defined by fix is only possible under call-by-need. With call-by-value the most we can have is the Y combinator.
See: Sharing vs. non-sharing fixed-point combinator and its linked entries and comments (among them, this, and its links, like Can fold be used to create infinite lists?).
When I was in high school, I figured out how to program my TI-84 Plus calculator to do quadratic equations for me. Like the goody-two-shoes I was, I deleted the program before the final exam. I am trying to recreate the program now, but it's not working well. Here's my code:
:Prompt A, B, C
:(-B+√(B²-4AC))/2A→Y
:(-B-√(B²-4AC))/2A→Z
:Disp Y
:Disp Z
(→ corresponds to the STO> (store) button on the calculator, which allows a user to set a value for a given letter variable.)
As far as I can tell, this should work. The math and the parentheses seem to be in order, the Prompt function works (after the program finishes, asking the calculator to print A, B, and C match the values stored from the last time the program was run).
When I ask it to calculate quadratic equations that I already know the answers to, it gives me funny numbers. Entering A=1, B=-3, C=2, which should return x-intercept values of 1 and 2, returns 2 and 0 instead. The x-intercepts of 0=3x²-10x+7 are 1 and 7/3, but the calculator returns 21 and 0. I can't reproduce it right now, but the this program has also returned some imaginary numbers where there shouldn't have been.
What's wrong with this code? The math works (inputting the second and third lines of code into the calculator to calculate, as opposed to lines of code in a program, after storing values in the variables does return the correct value), the Prompt and Disp functions work; what's wrong here?
Order of operations strikes again. The expression
(-B+√(B²-4AC))/2A
is being parsed as
((-B+√(B²-4AC))/2)*A
Add parentheses to /(2A) to fix this.
I like solving my math problems(high school) using R as it is faster than writing on a piece of paper. One problem I'm having is that I have to keep writing the multiplication sign, example:
9x^2 + 24x + 16 yields = Error: unexpected symbol in "9x"
Is there any way in R to multiply 4x, without having to write 4*x but only 4x?
Would save me some time in having to write one extra character the whole time! Thanks
No. Having a number in front of a character without any space simply isn't valid syntax in R.
Take a step back and look at the syntax rules for, say, Excel, Matlab, Python, Mathematica. Every language has its rules, generally (:-) ) with good reason. For example, in R, the following are legal object names:
foo
foo.bar
foo1
foo39
But 39foo is not legal. So if you wanted any sequence [0-9][Letters] or the reverse to indicate multiplication, you'd have a conflict with naming rules.
I have been playing with an implementation of lookandsay (OEIS A005150) in J. I have made two versions, both very simple, using while. type control structures. One recurs, the other loops. Because I am compulsive, I started running comparative timing on the versions.
look and say is the sequence 1 11 21 1211 111221 that s, one one, two ones, etc.
For early elements of the list (up to around 20) the looping version wins, but only by a tiny amount. Timings around 30 cause the recursive version to win, by a large enough amount that the recursive version might be preferred if the stack space were adequate to support it. I looked at why, and I believe that it has to do with handling intermediate results. The 30th number in the sequence has 5808 digits. (32nd number, 9898 digits, 34th, 16774.)
When you are doing the problem with recursion, you can hold the intermediate results in the recursive call, and the unstacking at the end builds the results so that there is minimal handling of the results.
In the list version, you need a variable to hold the result. Every loop iteration causes you to need to add two elements to the result.
The problem, as I see it, is that I can't find any way in J to modify an extant array without completely reassigning it. So I am saying
try. o =. o,e,(0&{y) catch. o =. e,(0&{y) end.
to put an element into o where o might not have a value when we start. That may be notably slower than
o =. i.0
.
.
.
o =. (,o),e,(0&{y)
The point is that the result gets the wrong shape without the ravels, or so it seems. It is inheriting a shape from i.0 somehow.
But even functions like } amend don't modify a list, they return a list that has a modification made to it, and if you want to save the list you need to assign it. As the size of the assigned list increases (as you walk the the number from the beginning to the end making the next number) the assignment seems to take more time and more time. This assignment is really the only thing I can see that would make element 32, 9898 digits, take less time in the recursive version while element 20 (408 digits) takes less time in the loopy version.
The recursive version builds the return with:
e,(0&{y),(,lookandsay e }. y)
The above line is both the return line from the function and the recursion, so the whole return vector gets built at once as the call gets to the end of the string and everything unstacks.
In APL I thought that one could say something on the order of:
a[1+rho a] <- new element
But when I try this in NARS2000 I find that it causes an index error. I don't have access to any other APL, I might be remembering this idiom from APL Plus, I doubt it worked this way in APL\360 or APL\1130. I might be misremembering it completely.
I can find no way to do that in J. It might be that there is no way to do that, but the next thought is to pre-allocate an array that could hold results, and to change individual entries. I see no way to do that either - that is, J does not seem to support the APL idiom:
a<- iota 5
a[3] <- -1
Is this one of those side effect things that is disallowed because of language purity?
Does the interpreter recognize a=. a,foo or some of its variants as a thing that it should fastpath to a[>:#a]=.foo internally?
This is the recursive version, just for the heck of it. I have tried a bunch of different versions and I believe that the longer the program, the slower, and generally, the more complex, the slower. Generally, the program can be chained so that if you want the nth number you can do lookandsay^: n ] y. I have tried a number of optimizations, but the problem I have is that I can't tell what environment I am sending my output into. If I could tell that I was sending it to the next iteration of the program I would send it as an array of digits rather than as a big number.
I also suspect that if I could figure out how to make a tacit version of the code, it would run faster, based on my finding that when I add something to the code that should make it shorter, it runs longer.
lookandsay=: 3 : 0
if. 0 = # ,y do. return. end. NB. return on empty argument
if. 1 ~: ##$ y do. NB. convert rank 0 argument to list of digits
y =. (10&#.^:_1) x: y
f =. 1
assert. 1 = ##$ y NB. the converted argument must be rank 1
else.
NB. yw =. y
f =. 0
end.
NB. e should be a count of the digits that match the leading digit.
e=.+/*./\y=0&{y
if. f do.
o=. e,(0&{y),(,lookandsay e }. y)
assert. e = 0&{ o
10&#. x: o
return.
else.
e,(0&{y),(,lookandsay e }. y)
return.
end.
)
I was interested in the characteristics of the numbers produced. I found that if you start with a 1, the numerals never get higher than 3. If you start with a numeral higher than 3, it will survive as a singleton, and you can also get a number into the generated numbers by starting with something like 888888888 which will generate a number with one 9 in it and a single 8 at the end of the number. But other than the singletons, no digit gets higher than 3.
Edit:
I did some more measuring. I had originally written the program to accept either a vector or a scalar, the idea being that internally I'd work with a vector. I had thought about passing a vector from one layer of code to the other, and I still might using a left argument to control code. With I pass the top level a vector the code runs enormously faster, so my guess is that most of the cpu is being eaten by converting very long numbers from vectors to digits. The recursive routine always passes down a vector when it recurs which might be why it is almost as fast as the loop.
That does not change my question.
I have an answer for this which I can't post for three hours. I will post it then, please don't do a ton of research to answer it.
assignments like
arr=. 'z' 15} arr
are executed in place. (See JWiki article for other supported in-place operations)
Interpreter determines that only small portion of arr is updated and does not create entire new list to reassign.
What happens in your case is not that array is being reassigned, but that it grows many times in small increments, causing memory allocation and reallocation.
If you preallocate (by assigning it some large chunk of data), then you can modify it with } without too much penalty.
After I asked this question, to be honest, I lost track of this web site.
Yes, the answer is that the language has no form that means "update in place, but if you use two forms
x =: x , most anything
or
x =: most anything } x
then the interpreter recognizes those as special and does update in place unless it can't. There are a number of other specials recognized by the interpreter, like:
199(1000&|#^)199
That combined operation is modular exponentiation. It never calculates the whole exponentiation, as
199(1000&|^)199
would - that just ends as _ without the #.
So it is worth reading the article on specials. I will mark someone else's answer up.
The link that sverre provided above ( http://www.jsoftware.com/jwiki/Essays/In-Place%20Operations ) shows the various operations that support modifying an existing array rather than creating a new one. They include:
myarray=: myarray,'blah'
If you are interested in a tacit version of the lookandsay sequence see this submission to RosettaCode:
las=: ,#((# , {.);.1~ 1 , 2 ~:/\ ])&.(10x&#.inv)#]^:(1+i.#[)
5 las 1
11 21 1211 111221 312211