Info

This question is closed. Reopen it to edit or answer.

is this working correctly

1 view (last 30 days)
Mio
Mio on 19 Apr 2015
Closed: MATLAB Answer Bot on 20 Aug 2021
1
  6 Comments
John D'Errico
John D'Errico on 22 Apr 2015
Edited: John D'Errico on 22 Apr 2015
Note that I do show how to solve the problem in the answer I gave. In fact, IF you look, you will find that I show how to solve it without ANY built-in functions, (ok, besides division, multiplication, addition, and probably colon. But if you can't use addition and multiplication, then you virtually can't use MATLAB.) The pythagSum.m code is actually pretty nice, and extremely efficient, able to almost immediately solve the problem for any value of L no larger then around 2^50 or so.
Star Strider
Star Strider on 25 Apr 2015
‘Mio’ deleted his Question. For the record, is was essentially the same as the one in the link I provided in my ‘22 Apr 2015 at 13:15’ Comment.

Answers (1)

Star Strider
Star Strider on 19 Apr 2015
This may get you started:
The output of ‘triple’ should be zero (or close to it) for all triplets that meet the criteria for Pythagorean triplets.
triple = @(a,b,c) a.^2 + b.^2 - c^2;
There are likely elegant ways to go about it, knowing the properties of them (and I believe John D’Errico has recently opined on this very topic in Unique triples: Length of wire bent into triangle), so mayhap you would want to give that a go.
Or, you could generate overnight millions of triplets of random numbers and feed it to my ‘triple’ function, write code to screen out all those that did not make the cut (triple > 1E-8) and save the ones that did.
Just Bear in mind that Polar Bears’ lives may hinge on your decision and the efficiency of your computations.
  3 Comments
Star Strider
Star Strider on 19 Apr 2015
There were a few problems with your code:
1. The ‘triple’ function needs three arguments. You didn’t give it any.
2. The conditional test was reversed. The correct test is ‘less than or equal’, ‘<=’. (The ‘greater than or equal’ is ‘>=’.)
I made those changes and added a matrix to store the successful tesults:
triple = @(a,b,c) a.^2 + b.^2 - c^2;
kt = 0;
for k = 1:100
a = rand;
b = rand;
c = rand;
trip_chk = triple(a,b,c);
if trip_chk <= 1E-8
fprintf(1,'\nSuccess with %.4f, %.4f, %.4f\n',a,b,c);
kt = kt + 1;
trip_tmx(kt,:) = [a, b, c];
else
fprintf(1,'\nNot a Pythagorean triple: %.4f, %.4f, %.4f\n',a,b,c);
end
end
This works. You might also try randi for integers >0, for example:
a = randi(1E+6);
b = randi(1E+6);
c = randi(1E+6);
to test random integers from 1 to 1E+6.
Star Strider
Star Strider on 22 Apr 2015
It would work to define a triple.
But if you’re doing the ‘bent wire’ problem, John D’Errico has already explored it thoroughly in the post I linked to. There is no need to revisit it here.

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!